Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript,将函数添加到原型_Javascript_Prototype_Currying - Fatal编程技术网

javascript,将函数添加到原型

javascript,将函数添加到原型,javascript,prototype,currying,Javascript,Prototype,Currying,在javascript中,是否可以使用类似于咖喱的东西向原型添加函数 我尝试使用此代码 var helloGoodBye = function (name, fun) { return function(message) { console.log('hello : ' + name); console.log(message); console.log('byebye : ' + name); return fun(message) }

在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

这是因为
this
inside
func
不是类的实例。它是全局对象
窗口
hellogoodbay
返回的匿名函数将其
this
设置为类的实例(它是附加到原型的函数)
func
是一个被困在闭包中的匿名函数,但它与类本身的实例无关

使用诸如
Function.prototype.call等的替代方法来明确指定

var hellogoodbay=函数(名称,乐趣){
返回函数(消息){
log('hello:'+name);
控制台日志(消息);
console.log('byebye:'+名称);
return fun.call(this,message);//在此作用域中使用this,该作用域将是对象的实例
}                                                                                           
}
var机器=功能(){
this.state='green';
};
Machine.prototype={
绿色:hellogoodbay('green',函数(消息){
this.state='red';
}),
红色:hellogoodbay('red',函数(消息){
this.state='green';
})
}
var sm=新机器();
控制台日志(sm);
sm[sm.state](“第一条消息”);

sm[sm.state](“第二条消息”)是的,您只需要让该方法调用接收方对象上的
fun
回调。使用:

function helloGoodBye(name, fun) {
  return function(message) {
    console.log('hello : ' + name);
    console.log(message);
    console.log('byebye : ' + name);
    return fun.call(this, message);
//            ^^^^^ ^^^^
  }                                                                                           
}