When it comes to this, you have to mention function. Due to the different call function objects, leading to the different points of this. function is also an object that needs to be performed in a particular environment. Figure out the two most common methods of function you can basically understand the use of this.
The two methods of function: call and apply
-
applymethod: Can hijack another object method, inherited property of another objectFunction.apply(obj,args)obj: this object will replace thethisobject in theFunctionclassargs: this is an Array, it will be passed as a parameterFunction(args-->arguments)
function Person(name,age) {
this.name = name;
this.age = age;
}
function Student(name,age,sex) {
Person.apply(this,arguments);
this.sex = sex;
}
var student = new Student("barrychen38",22,"man");
console.log("name:" + student.name + " age:" + student.age + " sex:" + student.sex);
//=> name:barrychen38 age:22 sex:man-
callmethod: have the same meaning withapply, but it is not the same parameter listFunction.call(obj,[param1[,param2[,…[,paramN]]]])obj: this object will replace thethisobject in theFunctionclassparams: this is a parameter list
function print(word) {
console.log(this + word);
}
print.call("Hello ", "World!"); //=> Hello World!Generally speaking, functionName(arg) can be directly replaced by functionName.call(window, arg), this makes it clear where the various parameters are pointing
Anonymous function is the same as the substitution method:
(function(name){
console.log(name);
})("Hello");
// equivalent to
(function(name){
console.log(name);
}).call(window, "Hello");The function is called as the object’s property is different:
var person = {
name: "barrychen38",
sex: function(sex) {
console.log(this.name + " is " + sex);
}
};
person.sex("man"); //=> barrychen38 is man
// equivalent to
person.sex.call(person, "man"); //=> barrychen38 is manWhen using the call method here, this points to the object itself.
call method can also be used for constructors:
function Person(name) {
this.name = name;
}
var obj = new Person("barrychen38");
console.log(obj.name); //=> barrychen38The key is to understand the new operator (not explained in detail):
var obj = {};
obj.__proto__ = Person.prototype;
Person.call(obj);From above we can figure out this method:
functionName(arg) => functionName.call(window, arg)obj.functionName(arg) => obj.functionName.call(obj, arg)