通常,调用 this
就可以了;但我在另一个上下文中调用该方法,因此 this
引用该上下文而不是“父”对象。
代码如下:
var someConfig = {
things: [
{
attr1: 'foo',
attr2: 'bar',
action: function() {
console.log(this);
}
}
]
}
function Constructor(config) {
var self = this;
self.name = 'test';
self.things = config.things;
$.each(self.things, function(i, thing) {
thing.action();
});
}
var obj = new Constructor(someConfig);
console.log(obj);
Here's a jsfiddle 。目标是让控制台中的两个对象相同,但 action
方法上下文中的 this
返回 action 所要执行的原始对象
属于,而不是构造函数。
我唯一能想到的就是将 self
传递到 action
中,但我认为还有更好的方法。
最佳答案
首先,关于您的代码的几点说明。您的配置属性是 uniqueAction
但后来您将其称为 config.action
。当您调用obj.action
时您需要将其作为函数调用,例如: obj.action();
考虑到这一点,以下内容似乎可以满足您的要求......
var config = {
action: function() {
console.log(this.name);//<- IMPORTANT PART
}
}
function Constructor(config) {
var self = this;
self.name = 'test';
self.action = config.action;
}
var obj = new Constructor(config)
obj.action();
请注意 console.log
现在调用使用 this.name
而不是self.name
.
关于javascript - 传递给构造函数的函数可以访问构造函数的其他属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14262016/