【问题标题】:Place references to prototype method in prototype object as dictionary [duplicate]将原型方法的引用放在原型对象中作为字典[重复]
【发布时间】:2015-04-09 12:30:04
【问题描述】:

在我的小脑袋里,我无法解释如何正确引用对象原型中的方法:

function A(){}
A.prototype.action = function(){}
A.prototype.dict = { action: this.action } // Mistake here.
var a = new A();
a.dict.action(); // -> undefined, but I expect a call of 'A.prototype.action' or other function if I override it in 'a'

【问题讨论】:

  • a = new A; 应该是var a = new A();当你让它的其余部分工作时。您想用该代码实现什么目标?
  • 请在适当的地方使用var,并与分号保持一致。你(和你的同事)总有一天会感谢你的。
  • @Cᴏʀʏ,这只是我的问题的快速输入示例。当然,我总是使用 'var' 和分号。
  • dict 方法在做什么?为什么不能直接打电话给a.action()
  • @Andy,我只需要将原型方法的引用放在对象中。该对象是字符串(事件类型的文本表示)和相应操作(函数)的映射。此对象用作默认对象,可以在继承对象中覆盖。

标签: javascript


【解决方案1】:

您尚未真正解释为什么需要此功能,但以下内容应该可以帮助您避免遇到的错误。这是否是好的做法,我留给你研究。

function A() {
    var self = this;
    this.dict = {
        action: function() {
            // by default, A.dict.action calls A.action
            return self.action();
        }
    };
}

// Define A.action
A.prototype.action = function() {
    console.log('prototype');
};

// Let's test it out
var a = new A();
a.dict.action(); // prints 'prototype'

// Override it on instance a
a.dict.action = function() {
  console.log('overridden');
};
a.dict.action(); // prints 'overridden'

// Let's create a new instance of A: b
var b = new A();
b.dict.action(); // prints 'prototpye'

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 2015-11-16
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    相关资源
    最近更新 更多