在JS中有4种方法可以调用函数。
作为函数调用一一如果一个函数没有作为方法、构造函数、apply、 call调用时,此时this指 向的是window对象(非严格模式)
//Global Scope
function add(a,b){
console. log(this);
return a + b;
}
add(1,5); // 打印"window"对象和 6
const o = {
method(callback) {
callback() ;
}
o. method (function () {
console. log (this) ; // 打印"window"对象
});
作为方法调用——如果一个对象的属性有一个函数的值,我们就称它为方法。调用该方法时, 该方法的this值指向该对象。
const details = {
name : "Marko",
getName () {
return this. name;
}
}
details. getName(); // Marko
作为构造函数的调用-如果在函数之前使用new关键字调用了函数,则该函数称为构造函数。 构造函数里面会默认创建一个空对象,并将this指向该对象。
function Employee(name, position, yearHired) {
//创建一个空对象{}
//然后将空对象分配给“this”关键字
// this = {};
this. name = name;
this. position = position;
this. yearHired = yearHired;
//如果没有指定return,这里会默认返回this
};
const emp = new Employee("Marko Polo", "Software Developer", 2017);
使用apply和call方法调用——如果我们想显式地指定一个函数的this值,我们可以使用这 些方法,这些方法对所有函数都可用。
const objl = {
result:0
};
const obj2 = {
result:0
};
function reduceAdd(){
let result = 0;
for(let i = 0, len = arguments. length; i < len; i++){
result += arguments[i];
}
this.result = result;
}
reduceAdd. apply(objl, [1, 2, 3, 4, 5]); // reduceAdd 函数中的 this 对象将是 objl
reduceAdd. call (obj2, 1, 2t 3, 4, 5) ; // reduceAdd 函数中的 this 对象将是 obj2
Was this helpful?
0 / 0