javascript,将函数添加到原型
在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) }
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
insidefunc
不是类的实例。它是全局对象窗口
。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);
// ^^^^^ ^^^^
}
}