我正在使用 JavaScript 原型(prototype)链接技术来链接函数,如下所示:
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
原型(prototype)添加更多功能。
如果我只是简单地执行以下操作,则不会起作用:
foo.prototype.baz = function () {
alert(this.arg);
}
foo("hello").baz();
但是,如果将 fn
分配给 foo
(func.functions = fn;
),如 foo
中所示code> 私有(private)闭包我可以执行以下操作,它将起作用:
foo.functions.prototype.baz = function () {
alert(this.arg);
}
foo("hello").baz();
还有其他方法可以达到这个目的吗?
最佳答案
我认为你没有必要把这个问题复杂化。您可以通过简单地执行以下操作来链接:
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')
注意:点击运行代码片段
查看输出
就是这样!
编辑:
您还可以使用 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')
关于javascript - 在闭包之外继承 javascript 函数原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42774067/