对象中的函数和对“this”属性的访问 - 失败
Function in object and access to 'this' property - failed
请看此示例代码:
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();
相关文章:
- JavaScript Pub/Sub属性访问问题
- AngularJS:如何用同一对象的另一个属性访问一个属性
- Ember JS属性访问器
- 对方法或属性访问的意外调用
- 对jQuery中IE8的方法或属性访问的意外调用
- 对方法或属性访问的意外调用.在JQUERY
- XDomainRequest onload上对方法或属性访问的意外调用
- Javascript属性访问速度:var.properties与var[“属性”]的区别
- 从函数属性访问对象属性;不适用于Firefox
- 重写内部 HTML 属性访问
- (仅在IE中)SCRIPT65535:对方法或属性访问的意外调用.主.js,第 152 行字符 28
- 使用表达式属性访问不同的模型模板选项
- jQuery mobile 1.1.0 滑块:JS-对象属性访问
- Ractive.js,通过命名属性访问父属性
- jQuery验证插件addMethod可以通过属性访问
- 如何使用动态属性访问对象
- 我无法通过 Firefox 中的“for”属性访问标签,但可以在 Chrome 中访问标签
- JavaScript 对象原型属性访问
- 使用虚拟属性访问猫鼬模型中的嵌套文档
- 是否可以在Javascript/Coffeescript中的属性访问期间自动调用函数调用