继承它之外的javascript函数原型

时间:2017-03-13 21:50:20

标签: javascript closures prototype chaining

我正在使用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();

但是,如果fnfoo} func.functions = fn; foo foo.functions.prototype.baz = function () { alert(this.arg); } foo("hello").baz(); {{1}} {{1}} {{1}} {{1}} {{1}} {}} {}} {}} >

{{1}}

还有其他方法可以达到这个目的吗?

1 个答案:

答案 0 :(得分:3)

我认为你不一定过于复杂。你可以简单地做到这一点:



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 < / strong> 查看输出

那就是它!

编辑:

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

&#13;
&#13;
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')
&#13;
&#13;
&#13;