如何使用“原型”定义子方法?

时间:2017-01-21 15:04:34

标签: javascript class methods prototype

当我用这种方式定义带有方法和子方法的javascript类时,它可以工作:

function Controller () {
    this.OrdersSyncFreq = 3000; //ms

    this.syncOrders = function () {};
    this.syncOrders.start = function () { console.log("start was called"); };
    this.syncOrders.stop = function () { console.log("stop was called"); };
}

但是如何使用“prototype”定义函数Controller.syncOrders.start()?这样的事情不起作用:

Controller.prototype.syncOrders.stop = function () {
    console.log("The NEW stop was called");
}

1 个答案:

答案 0 :(得分:-1)

再看一下,我发现它可以这样写:

function Controller () {
    this.OrdersSyncFreq = 3000; //ms
    this.syncOrders();  // have to be called at init to make sure the definitions of start and stop will be active. 
}

Controller.prototype.syncOrders = function () {

    this.syncOrders.start = function () {
        console.log("Start was called, frequence is: ",this.OrdersSyncFreq);
    }.bind(this);   // .bind(this)  is needed to have access this of your controller instance


    this.syncOrders.stop = function () {
        console.log("Stop was called, frequence is: ",this.OrdersSyncFreq);
    };

}

// run the code
var app = new Controller();
app.syncOrders.start();  // console: Start was called, frequence is:  3000
app.syncOrders.stop();  // console: Stop was called, frequence is:  undefined

syncOrders的方法 - Start()和Stop()不需要原型化,因为syncOrders不会被实例化。

无论如何,我不确定这样做是否真的有意义。我这样做只是因为命名空间。可能最好使用更简单的内容,例如syncOrdersStart()syncOrdersStop()