Javascript 对象中的函数和访问';这';属性-失败
请看以下示例代码:Javascript 对象中的函数和访问';这';属性-失败,javascript,scope,Javascript,Scope,请看以下示例代码: var functions = { testFunction: function(){ console.log('testFunction()', this, this.someProperty); } }; functions.testFunction.someProperty = 'someValue'; functions.testFunction(); 为什么第2行中的.someProperty未定义?因为您可以从第二个参数控制台中看到。log输
var functions = {
testFunction: function(){
console.log('testFunction()', this, this.someProperty);
}
};
functions.testFunction.someProperty = 'someValue';
functions.testFunction();
为什么第2行中的.someProperty未定义?因为您可以从第二个参数
控制台中看到。log
输出-此
指的是函数
对象,而不是测试函数
匿名函数
此任务将满足您的要求:
functions.someProperty = 'someValue';
var函数={
testFunction:function(){
log('testFunction()',functions,functions.someProperty);
}
};
functions.someProperty='someValue';// 试着这样做:-
var functions = {
testFunction: function(){
console.log('testFunction()', functions, functions.someProperty);
}
};
functions.someProperty = 'someValue';
functions.testFunction();
obj.method()
是obj.method.call(obj)
的语法糖
因此,当您执行functions.testFunction()
时,此函数调用中的this
引用指向函数
要以这种方式访问它,请执行以下操作:
var functions = {
testFunction: function(){
console.log(this.testFunction.someProperty); //"someValue"
}
};
functions.testFunction.someProperty = 'someValue';
functions.testFunction();
this
关键字在本文中得到了很好的解释
var functions = {
testFunction: function(){
console.log(this.testFunction.someProperty); //"someValue"
}
};
functions.testFunction.someProperty = 'someValue';
functions.testFunction();