简体   繁体   English

在对象方法链(JS)中添加sleep方法

[英]Add a sleep method in a object method chain(JS)

I'm trying to add a sleep method in a object, which can be called in the middle of a method chain. 我正在尝试在对象中添加一个sleep方法,该方法可以在方法链的中间调用。 I considered to use the setTimeout(), but the javascript thread could not be blocked, and it can not output the correct order I want. 我考虑使用setTimeout(),但是无法阻止javascript线程,并且它无法输出所需的正确顺序。

<div id="test"></div>

 function hello(str){
  var text = document.getElementById("text");
  this.eat = function(kind){
    text.innerHTML += "<p>Eat "+ kind + "</p>";
    return this;
  }
  this.sleep = function(delay){
    setTimeout(function(){
      text.innerHTML += "<p>Sleep "+delay + "</p>";
    }, delay);
    return this;
  }
  text.innerHTML += "<p>Hello, "+ str + "</p>";
  return this;
}
var test = hello("guy").sleep(3000).eat("dinner"); 
/* I want an output as: 
      Hello, guy -> (wait 3 secs) Sleep 3000 -> Eat dinner
   But actually the output is:
      Hello, guy -> Eat dinner -> (wait 3 secs) Sleep 3000    
*/  

Does anyone have any ideas on it? 有人对此有任何想法吗? Shoud I use the prototype, or some other ways to deal with it? 我应该使用原型还是其他某种方式来处理它? What's more, if I want to add another method, named sleepFirst in this object. 此外,如果我想在该对象中添加另一个名为sleepFirst方法。 When I call it like this: 当我这样称呼它时:

var test2 = hello("boys").sleepFirst(2000).eat("lanch")

it outputs: 它输出:
(wait 2 secs) sleepFirst 2000 -> Hello, boys -> Eat lanch (等待2秒)sleepFirst 2000->您好,男孩->吃牧场

What should I do? 我该怎么办?
(Postscript: I am a beginner in Web Development, maybe someone has asked a similar question before but I had searched for a long time and can't find it out T^TI am a Chinese guy and sorry that my English may seem not so good. Thanks ~~) (后记:我是Web开发的初学者,也许以前有人问过类似的问题,但我搜索了很长时间,却找不到T ^ TI是中国人,很抱歉我的英语似乎不太像好,谢谢~~)

@RobG convinced me to rewrite your piece of code using a real object definition. @RobG说服我使用真实的对象定义来重写您的代码。 JsFiddle here . JsFiddle 在这里

var sleeper = {
    text: document.getElementById("text"),
    eat: function (kind) {
        text.innerHTML += "<p>Eat " + kind + "</p>";
        return this;
    },
    sleep: function (delay, func, param) {
        setTimeout(function () {
            func(param);
            //text.innerHTML += "<p>Sleep " + delay + "</p>";
        }, delay);
        return this;
    },
    hello: function (str) {
        text.innerHTML += "<p>Hello, " + str + "</p>";
        return this;
    }
};

sleeper.hello("guy").sleep(3000, sleeper.eat, "dinner");

It's way much better. 好多了。 But this way you won't be abble to perform a chain of more than one call. 但是这样一来,您就不会厌倦执行多个通话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM