Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对象中的函数和访问';这';属性-失败_Javascript_Scope - Fatal编程技术网

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();