【问题标题】:inherit javascript function prototype outside it closure在它闭包之外继承javascript函数原型
【发布时间】:2017-03-13 21:50:20
【问题描述】:

我正在使用 JavaScript 原型链接技术来链接函数,如下所示:

var foo = (function () {
    function fn(arg) {
        if (!(this instanceof fn)) {
            return new fn(arg);
        }
        this.arg = arg;
        return this;
    }
    var func = function (element) {
        return fn(element);
    };
    fn.prototype = {
        bar: function () {
            return this;
        }
    }
    func.functions = fn;
    return func;
}());

我想知道如何访问fn.prototype,这样我就可以在foo 原型的闭包之外添加更多功能。

如果我只是简单地这样做,它是行不通的:

foo.prototype.baz = function () {
     alert(this.arg);
}
foo("hello").baz();

但是,如果 fn 分配给 foo (func.functions = fn;),如 foo 私人闭包中所示,我可以执行以下操作,它会起作用:

foo.functions.prototype.baz = function () {
     alert(this.arg);
}
foo("hello").baz();

还有其他方法可以实现吗?

【问题讨论】:

  • 你确定你的意思是baz而不是bar
  • 还有这行,func.functions = fn 在这种情况下没有任何作用,因为您没有在 func 正文中使用 fnthis.fn
  • 您可以利用对象通过引用而不是值传递的事实,并执行以下操作:func.prototype = fn.prototype; 因此,当更改 foo 的原型时,fn 的原型会更改为好吧!
  • 是的,baz 是我想链接的新功能。老实说,我发现很难解释这种情况,希望这是有道理的。

标签: javascript closures prototype chaining


【解决方案1】:

我认为您没有必要将其复杂化。您可以通过简单地执行以下操作进行链接:

const foobar = function(){return this} // Initialize a new Object
const foo = text => {
    const me = new foobar()
    me.text = text
    me.bar = a => (alert(me.text+": "+a), me)
    return me
}

foo('A').bar('Test').bar('Test chained')

// Update the foobar class with baz
foobar.prototype.baz = function() {alert('BAZ worked!');return this}

foo('B').bar('1').baz().bar('2')

注意:点击Run code snippet查看输出

就是这样!

编辑:

您也可以使用 ES6 类来执行此操作,例如:

class foobar {
  constructor(text) {
    this.text = text;
  }
  bar(a) {alert(this.text+": "+a);return this}
}

const foo = text => new foobar(text)

foo('A').bar('Test').bar('Test chained')

// Update the foobar class with baz
foobar.prototype.baz = function() {alert('BAZ worked!');return this}

foo('B').bar('1').baz().bar('2')

【讨论】:

  • 绝对!如果此答案解决了您的问题,请务必将其标记为已接受
猜你喜欢
  • 2021-11-14
  • 2014-05-08
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
  • 2018-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多