上下文函数时如何获取父对象?
How to get parent object when context is function?
我想为对象方法编写当前函数。我想让这成为可能:
Function.prototype.curry = function (){
var originalFunction = this;
var args = ...; // here goes logic embracing arguments
var bind = ???; //how to get reference to someObject ???
return function(){
return originalFunction.apply(bind, args);
}
}
var someObject = {
doSomething : function (param1, param2, param3){
//do something with params
return param1 + ' ' + param2 + ' ' + param3;
}
}
someObject.doSomethingCurried = someObject.doSomething.curry('param1 value', 'param2 value');
//I want to be able to do:
someObject.doSomethingCurried('param3 value')'
有 some tricks,但实际上你应该将上下文作为第一个参数传递,就像原生 bind
.
// Code goes here
Function.prototype.curry = function (context,arg){
var originalFunction = this;
var args = Array.prototype.slice.call(arguments,1) ; // here goes logic embracing arguments
var bind = context; //how to get reference to someObject ???
return function(){
return originalFunction.apply(bind, args.concat(Array.prototype.slice.call(arguments)));
}
}
var someObject = {
myObj:"Myobj",
doSomething : function (param1, param2, param3){
console.log(this);
//do something with params
return param1 + ' ' + param2 + ' ' + param3;
}
}
someObject.doSomethingCurried = someObject.doSomething.curry(someObject,'param1 value', 'param2 value');
//I want to be able to do:
console.log(someObject.doSomethingCurried('param3 value'));
我想为对象方法编写当前函数。我想让这成为可能:
Function.prototype.curry = function (){
var originalFunction = this;
var args = ...; // here goes logic embracing arguments
var bind = ???; //how to get reference to someObject ???
return function(){
return originalFunction.apply(bind, args);
}
}
var someObject = {
doSomething : function (param1, param2, param3){
//do something with params
return param1 + ' ' + param2 + ' ' + param3;
}
}
someObject.doSomethingCurried = someObject.doSomething.curry('param1 value', 'param2 value');
//I want to be able to do:
someObject.doSomethingCurried('param3 value')'
有 some tricks,但实际上你应该将上下文作为第一个参数传递,就像原生 bind
.
// Code goes here
Function.prototype.curry = function (context,arg){
var originalFunction = this;
var args = Array.prototype.slice.call(arguments,1) ; // here goes logic embracing arguments
var bind = context; //how to get reference to someObject ???
return function(){
return originalFunction.apply(bind, args.concat(Array.prototype.slice.call(arguments)));
}
}
var someObject = {
myObj:"Myobj",
doSomething : function (param1, param2, param3){
console.log(this);
//do something with params
return param1 + ' ' + param2 + ' ' + param3;
}
}
someObject.doSomethingCurried = someObject.doSomething.curry(someObject,'param1 value', 'param2 value');
//I want to be able to do:
console.log(someObject.doSomethingCurried('param3 value'));