代码之家  ›  专栏  ›  技术社区  ›  JuanPablo

javascript,向原型添加函数

  •  3
  • JuanPablo  · 技术社区  · 9 年前

    在javascript中,是否可以使用类似于咖喱的东西向原型添加函数?

    我尝试使用此代码

    var helloGoodBye = function (name, fun) {
      return function(message) {
        console.log('hello : ' + name);
        console.log(message);
        console.log('byebye : ' + name);
        return fun(message)
      }                                                                                           
    }
    
    var Machine = function (){
      this.state = 'green';
    };
    
    Machine.prototype = {
      green: helloGoodBye('green', function (message){
        this.state = 'red';
      }),
      red: helloGoodBye('red', function (message){
        this.state = 'green';
      })
    }
    
    var sm = new Machine();
    
    sm[sm.state]('first message');
    sm[sm.state]('second message');
    

    我得到了这个输出

    "hello state: green"
    "first message"
    "byebye state: green"
    "hello state: green"
    "second message"
    "byebye state: green"
    

    但这种方式行不通,可能是因为 this.state this.state 生活在全球范围内。

    2 回复  |  直到 5 年前
        1
  •  2
  •   Bergi    9 年前

    fun receiver对象上的回调。使用 call :

    function helloGoodBye(name, fun) {
      return function(message) {
        console.log('hello : ' + name);
        console.log(message);
        console.log('byebye : ' + name);
        return fun.call(this, message);
    //            ^^^^^ ^^^^
      }                                                                                           
    }
    
        2
  •  1
  •   ibrahim mahrir    9 年前

    这是因为 this 在…内 func 不是您的类的实例。它是全局对象 window helloGoodBye 是一个有 设置为类的实例(它是附加到原型的函数)。

    使用替代方案,例如 Function.prototype.call 要明确指定 :

    var helloGoodBye = function (name, fun) {
      return function(message) {
        console.log('hello : ' + name);
        console.log(message);
        console.log('byebye : ' + name);
        return fun.call(this, message); // use the this in this scope which will be the instance of the object
      }                                                                                           
    }
    
    var Machine = function (){
      this.state = 'green';
    };
    
    Machine.prototype = {
      green: helloGoodBye('green', function(message) {
        this.state = 'red';
      }),
      red: helloGoodBye('red', function(message) {
        this.state = 'green';
      })
    }
    
    var sm = new Machine();
    
    console.log(sm);
    sm[sm.state]('first message');
    sm[sm.state]('second message');
    推荐文章