【问题标题】:How to define a sub method using "prototype"?如何使用“原型”定义子方法?
【发布时间】:2017-01-21 15:04:34
【问题描述】:

当我以这种方式定义一个带有方法和子方法的 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"); };
}

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

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

【问题讨论】:

  • 不,这从来没有真正奏效过,你不能在那些“方法”中使用this。只是不要这样做。使用常规前缀。
  • 这就是我在自己的答案尝试中使用 .bind(this) 的原因。 “常规前缀”是什么意思?
  • 只需调用方法.syncOrdersStop.syncOrdersStart(或带下划线)。
  • 是的,但这是我在自己的答案中推荐的结论类型!你有“-1”

标签: javascript class methods prototype


【解决方案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() 之类的更简单的东西可能会更好。

【讨论】:

  • 每次创建新实例时都会覆盖syncOrders.startsyncOrders.stop
  • 是的,没关系。在我的情况下,它只会被实例化 2 次。无论如何,这就是我写“我不确定这是否真的有意义”的原因......
  • 顺便说一句:我已经写了大约 20 分钟的问题。比我找到类似解决方案的东西。所以为了不要在这里得到负面评价(因为重复的问题或其他原因),我决定回答我仍然自己投入时间并再次投入 30 分钟的问题。现在我为此得到了负面评价。这不是很好的学习!
  • 当这个答案出现时问题就开始了,人们开始通过搜索引擎找到错误的答案,标记为正确只是为了保持分数。那么,你的学习体验就会很糟糕。
  • 您不会因为未回答或重复的问题而失去分数。如果某个答案被认为是错误的建议,或者建议的解决方案不起作用,则该答案会被否决。
猜你喜欢
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 1970-01-01
  • 2017-04-19
相关资源
最近更新 更多