[英]javascript, add function to prototype
在 javascript 中,是否可以使用類似於 curry 的東西向原型添加函數?
我嘗試使用此代碼
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
。
是的,您只需要讓該方法在接收者對象上調用fun
的回調。 使用call
:
function helloGoodBye(name, fun) {
return function(message) {
console.log('hello : ' + name);
console.log(message);
console.log('byebye : ' + name);
return fun.call(this, message);
// ^^^^^ ^^^^
}
}
這是因為this
inside func
不是你的類的實例。 它是全局對象window
。 helloGoodBye
返回的匿名函數是將其this
設置為類實例的函數(它是附加到原型的函數)。 func
是一個困在閉包中的匿名函數,但它與類本身的實例無關。
使用Function.prototype.call
之類的替代方法來顯式指定this
:
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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.