看这个示例代码:
var functions = {
testFunction: function(){
console.log('testFunction()', this, this.someProperty);
}
};
functions.testFunction.someProperty = 'someValue';
functions.testFunction();
为什么第 2 行中的this.someProperty未定义?
看这个示例代码:
var functions = {
testFunction: function(){
console.log('testFunction()', this, this.someProperty);
}
};
functions.testFunction.someProperty = 'someValue';
functions.testFunction();
为什么第 2 行中的this.someProperty未定义?
因为正如您通过第二个参数所看到的console.log输出 -this指的是functions对象,而不是testFunction匿名函数。
这个任务会做你想做的事:
functions.someProperty = 'someValue';
var functions = {
testFunction: function(){
console.log('testFunction()', functions, functions.someProperty);
}
};
functions.someProperty = 'someValue'; // <------ you should set value to functions's property
functions.testFunction();
试试这样: -
var functions = {
testFunction: function(){
console.log('testFunction()', functions, functions.someProperty);
}
};
functions.someProperty = 'someValue';
functions.testFunction();
obj.method()是 . 的语法糖obj.method.call(obj)。
因此,当您functions.testFunction()在this此函数调用内部进行引用时,指向functions.
要以这种方式访问它,您将执行以下操作:
var functions = {
testFunction: function(){
console.log(this.testFunction.someProperty); //"someValue"
}
};
functions.testFunction.someProperty = 'someValue';
functions.testFunction();
this关键字在这篇文章中有很好的解释。