2 回答

TA貢獻1875條經驗 獲得超5個贊
要鏈接功能,您需要返回this
或object
本身,您可以嘗試這樣的操作
這里
new bar()
將返回一個函數,foo()
將返回 obj,關于進一步
start
和end
方法調用,我們更新屬性和返回參考對象本身
我將如何制作一個對象,我可以指示在某些時候做什么。見示例:
function bar(){
// call/execute the start() code
// do something
// do some other thing
// do something else
// call/execute the end() code
}
foo=new bar();
foo()
.start(function(param){
console.log("start");
})
.end(function(param){
console.log("end");
})

TA貢獻1719條經驗 獲得超6個贊
您可以采用一些原型函數并返回一個隱式this的替代,一個帶邊界的函數this。
這些函數使用流暢的接口并返回this.
function Bar() {
return function() {
return this;
}.bind(this);
}
Bar.prototype.start = function (fn) { fn(); return this; };
Bar.prototype.end = function (fn) { fn(); return this; };
var foo = new Bar();
foo()
.start(function(param) {
console.log("start");
})
.end(function(param) {
console.log("end");
})
添加回答
舉報