3 回答
TA贡献1911条经验 获得超7个赞
您可以创建一个函数,该函数将调用一个参数,getSum但本身提供第一个参数。
TestClass.prototype.getSum = function() { //<–– normal function
return getSum.call( this, 1 );
// ^^^^ ^^^^ ^
// || || |
// forward this –++––––++ +–––––– pass a value for the first parameter
}
这将为您提供以下信息
function getSum (firstValue) { return firstValue + this.secondValue }
class TestClass {}
TestClass.prototype.getSum = function() {
return getSum.call(this, 1);
}
const obj = new TestClass()
obj.secondValue = 2
console.log(obj.getSum()) // 3
通常,将值绑定到函数中的参数的过程称为部分应用程序。例如,如果一个函数需要三个参数,那么您一开始只能设置两个,然后再设置最后一个。整个过程可以通过创建一个函数来处理这个抽象出来:
function partiallyApply(fn, ...params) {
return function(...moreParams) {
return fn.call(this, ...params, ...moreParams);
}
}
function takes4Parameters (a, b, c, d) {
return a + b + c + d;
}
const takes2Parameters = partiallyApply(takes4Parameters, 1, 2); // 1 + 2 + c + d
console.log("1 + 2 + 11 + 12 =", takes2Parameters(11, 12));
const takes1Parameter = partiallyApply(takes2Parameters, 3); // 1 + 2 + 3 + d
console.log("1 + 2 + 3 + 5 =", takes1Parameter(5));
const takesNoParameter = partiallyApply(takes1Parameter, 6); // 1 + 2 + 3 + 6
console.log("1 + 2 + 3 + 6 =", takesNoParameter());
使用那个高阶函数,我们可以更容易地推导getSum出TestClass
function getSum (firstValue) { return firstValue + this.secondValue }
function partiallyApply(fn, ...params) {
return function (...moreParams) {
return fn.call(this, ...params, ...moreParams)
}
}
class TestClass {}
TestClass.prototype.getSum = partiallyApply(getSum, 1);
//example of adding other partially applied methods:
TestClass.prototype.getSum2 = partiallyApply(getSum, 2);
TestClass.prototype.getSum3 = partiallyApply(getSum, 3);
TestClass.prototype.getSum4 = partiallyApply(getSum, 4);
const obj = new TestClass()
obj.secondValue = 2
console.log(obj.getSum()); // 3
console.log(obj.getSum2()); // 4
console.log(obj.getSum3()); // 5
console.log(obj.getSum4()); // 6
TA贡献1946条经验 获得超3个赞
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
function Sum(first, second) {
this.firstValue = first;
this.secondValue = second;
}
Sum.prototype.getSum = function() { return this.firstValue + this.secondValue }
var mysum = new Sum(50, 10);
document.getElementById("demo").innerHTML =
"Sum is" + mysum.getSum();
</script>
</body>
</html>
TA贡献1785条经验 获得超4个赞
让我知道这是否适合您。
function getSum(firstValue = 1) {
return firstValue + this.secondValue
}
// or
//function getSum() {
// const firstValue = arguments.length ? arguments[0] : 1;
// return firstValue + this.secondValue
//}
class Test {}
Test.prototype.getSum = getSum;
// or
// Test.prototype["getSum"] = getSum;
// or
// const methodName = "getSum";
// Test.prototype[methodName] = getSum;
const test = new Test();
test.secondValue = 100;
console.log(test.getSum()) // -> 101, firstValue is 1
console.log(test.getSum(11)) // -> 111, firstValue is 11
添加回答
举报