亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

帶有方法的 Javascript 對象

帶有方法的 Javascript 對象

一只斗牛犬 2021-11-18 17:08:14
我將如何制作一個對象,我可以指示在某些時候做什么。見示例: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");})
查看完整描述

2 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

要鏈接功能,您需要返回thisobject本身,您可以嘗試這樣的操作

  • 這里new bar()將返回一個函數,foo()將返回 obj,

  • 關于進一步startend方法調用,我們更新屬性和返回參考對象本身

我將如何制作一個對象,我可以指示在某些時候做什么。見示例:


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");

})


查看完整回答
反對 回復 2021-11-18
?
慕俠2389804

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");

    })


查看完整回答
反對 回復 2021-11-18
  • 2 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號