The content of this article is an introduction to several function calling methods pointed to by this in JS. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Beginners to JavaScript will always be confused about the this pointer. If you want to learn JavaScript in depth, you must first clarify several concepts related to this. In JavaScript, this always points to an object, but the specific object it points to is dynamically bound at runtime according to the function execution environment, not the environment when the function is declared. Except for the uncommon with and eval situations, in practical applications, this pointer can be roughly divided into the following four types.
When a function is called as a method of an object, this points to the object:
var person = { name: 'twy', getName: function() { console.info(this === person); // 输出true console.info(this.name); // 输出twy } } person.getName();
When When the function is called as an ordinary function, this in non-strict mode points to the global object:
function getName(){ // 非严格模式 console.info(this === window); // 浏览器环境下输出true } getName();
In strict mode this is undefined:
function getName(){ // 严格模式 "use strict" console.info(this === window); // 输出false } getName();
When new When an object is an object, this in the constructor points to the new object:
function person(){ // 构造函数 this.color = 'white'; } var boy = new person(); console.info(boy.color); // 输出white
Use Function.prototype.apply
or Function .prototype.call
can dynamically change the this pointer of the incoming function:
// 声明一个父亲对象,getName方法返回父亲的名字 var father = { name: 'twy', getName: function(){ return this.name; } } // 生命一个儿子对象,但是没有返回名字的功能 var child = { name: 'chy' } console.info(father.getName()); // 输出twy // 使用call或apply将father.getName函数里this指向child console.info(father.getName.call(child)); // 输出chy console.info(father.getName.apply(child)); // 输出chy
The above is the detailed content of Introduction to several function calling methods pointed to by this in JS. For more information, please follow other related articles on the PHP Chinese website!