我正在使用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();
{{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类来执行此操作,例如:
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;