简短描述:我正在使用带有函数声明、new 关键字和原型(prototype)方法的 OO Javascript(下面的示例)。我需要一种在对象的每个方法中引用“ self ”对象的方法。 “this”似乎只有在我直接调用该方法时才有效,否则“this”似乎指的是调用该方法的任何东西。
更多细节:这是我的对象的简化版本。
function Peer(id) {
this.id = id;
this.pc = new RTCPeerConnection(SERVER);
this.pc.onevent1 = this.onEvent1;
this.pc.onevent2 = this.onEvent2;
}
Peer.prototype.doSomething = function() {
// create offer takes one param, a callback function
this.pc.createOffer(this.myCallback);
};
Peer.prototype.onEvent1 = function(evt) {
// here this refers to the RTCPeerConnection object, so this doesn't work
this.initSomething(evt.data);
};
Peer.prototype.myCallback = function(data) {
// here this refers to the window object, so this doesn't work
this.setSomething = data;
};
Peer.prototype.initSomething = function(data) {
// use data
};
这是它的使用示例。
var peer = new Peer(1);
peer.doSomething();
// eventually something triggers event1
我尽量简化代码,并在注释中说明问题。我为第一个场景(调用 this.myCallback)创建了一个解决方法,方法是创建 this 的本地副本并将回调参数设为匿名函数,该函数使用我的 this 的本地副本调用我需要的函数。但是第二种情况比较麻烦(事件触发)。
我很好奇是否存在面向对象编程的不同模型,其中每个方法始终具有对父对象的正确引用,而不管该方法是如何调用的?或者是否有不同的方法来创建对象作为自定义对象的属性并将其事件绑定(bind)到自定义对象的方法?对不起,如果这是令人困惑的语言!请注意,我的问题与 RTCPeerConnection 无关,这恰好是我目前正在从事的项目。
我找到这篇文章:http://www.alistapart.com/articles/getoutbindingsituations但我不确定如何使用这些信息?
最佳答案
I was curious if there is a different model for Object Oriented programming in which every method always has a proper reference to the parent object, regardless of how the method was invoked?
是的,有:它叫做 Function.bind
.
function Peer(id) {
this.id = id;
this.pc = new RTCPeerConnection(SERVER);
this.pc.onevent1 = this.onEvent1.bind(this);
this.pc.onevent2 = this.onEvent2.bind(this);
}
同样,对于 myCallback
的 this
始终引用 Peer
实例:
Peer.prototype.doSomething = function() {
// create offer takes one param, a callback function
this.pc.createOffer(this.myCallback.bind(this));
};
关于Javascript OO引用这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14282605/