[英]javascript chaining function / function extends using IIFE expression
I've been looking for a way of extending a function in a straightforward way, like in C# extension method . 我一直在寻找一种以简单的方式扩展功能的方法,例如C#extension method 。
I've tried the following statement which I have found in this article Method Chaining in JavaScript and wich works fine. 我已经尝试了下面的语句,该语句在本文的JavaScript方法链接中找到,并且可以正常工作。
var FOO = function(){
this.whateverFunc = function(){
console.log("whatever func");
}
};
FOO.prototype.first = function(){
console.log("first func");
return this;
};
FOO.prototype.second = function(){
console.log("second func");
return this;
};
Then I can chain it: 然后,我可以将其链接:
var foo = new FOO();
foo.first().second();
//Output
//first func
//second func
BUT: My projects has the following "pattern": 但是:我的项目具有以下“样式”:
var FOO = (function(){
var foo{
firstFunc: function(){
//implement
},
secondFunc: function(){
//implement
},
}
return foo;
}());
It doesn't work even if I don't use IIFE. 即使我不使用IIFE,它也不起作用。
var FOO = function() { var foo{}; return foo; };
Is there a way to use chaining function whitin that pattern? 有没有一种使用链接功能的模式? How could I accomplish this(if this is possible!): 我如何才能做到这一点(如果可能的话!):
FOO.first().second();
Thanks. 谢谢。
The only issue with the code following 以下代码的唯一问题
BUT: My projects has the following "pattern": 但是:我的项目具有以下“样式”:
is missing =
at foo
declaration. 在foo
声明中缺少=
。
If IIFE uses arrow function the invoking parentheses should be last part of IIFE, instead of within outer parentheses. 如果IIFE使用箭头功能,则调用括号应位于IIFE的最后一部分,而不是位于外部括号内。
var FOO = (function() { var foo = { firstFunc: function() { //implement console.log(1); return this }, secondFunc: function() { //implement console.log(2); return this } } return foo; })(); FOO.firstFunc().secondFunc()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.