对象中的函数和对“this”属性的访问 - 失败

Function in object and access to 'this' property - failed

本文关键字:属性 访问 失败 this 函数 对象      更新时间:2023-09-26

请看此示例代码:

var functions = {
 testFunction: function(){
  console.log('testFunction()', this, this.someProperty);
 }      
};
functions.testFunction.someProperty = 'someValue';
functions.testFunction();

为什么第二行中的 this.some 属性未定义?

因为正如你通过第二个参数console.log输出所看到的那样 - this指的是functions对象,而不是testFunction匿名函数。

此作业将执行您想要的操作:

functions.someProperty = 'someValue';

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关键字在本文中得到了很好的解释。

尝试如下:-

var functions = {
 testFunction: function(){
  console.log('testFunction()', functions, functions.someProperty);
 }      
};
functions.someProperty = 'someValue';
functions.testFunction();
var functions = {
 testFunction: function(){
  console.log('testFunction()', functions, functions.someProperty);
 }      
};
functions.someProperty = 'someValue'; // <------ you should set value to functions's property
functions.testFunction();