为了账号安全,请及时绑定邮箱和手机立即绑定

带有方法的 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 关注
  • 125 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信