猿问

带有方法的 Javascript 对象

我将如何制作一个对象,我可以指示在某些时候做什么。见示例:


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

})


一只斗牛犬
浏览 126回答 2
2回答

慕田峪4524236

要链接功能,您需要返回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");})

慕侠2389804

您可以采用一些原型函数并返回一个隐式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");    })
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答