3 回答

TA貢獻1911條經(jīng)驗 獲得超7個贊
您可以創(chuàng)建一個函數(shù),該函數(shù)將調(diào)用一個參數(shù),getSum但本身提供第一個參數(shù)。
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
通常,將值綁定到函數(shù)中的參數(shù)的過程稱為部分應(yīng)用程序。例如,如果一個函數(shù)需要三個參數(shù),那么您一開始只能設(shè)置兩個,然后再設(shè)置最后一個。整個過程可以通過創(chuàng)建一個函數(shù)來處理這個抽象出來:
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());
使用那個高階函數(shù),我們可以更容易地推導(dǎo)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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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
添加回答
舉報