Javascript OO引用这个

标签 javascript oop

简短描述:我正在使用带有函数声明、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);
}

同样,对于 myCallbackthis 始终引用 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/

相关文章:

java - Java 变量太多?

Java - 从多种不同类型中挑选一个 ArrayList

c++ - 关于碰撞检测系统中类结构的建议

JavaScript 密码和用户名验证

javascript - 实时图表上的动态 x 轴?

javascript - 无服务器( Node AWS) "TypeError","errorMessage":"callback is not a function"

javascript - VueJS 自定义指令函数作为参数

javascript - 使用汇总将 TypeScript 构建到 JavaScript 时如何删除注释

c++ - 通用树的析构函数

oop - 在 TCL 中列出命名空间中任何类的所有实例