方法鏈 讓多個方法調用鏈接成單一語句,代碼更流暢。核心原理:每個方法返回 this (或新對象),使調用可連續。
$('#person')
.slideDown('slow')
.addClass('grouped')
.css('margin-left', '11px');
等價於:
var p = $('#person');
p.slideDown('slow');
p.addClass('grouped');
p.css('margin-left', '11px');
var Calculator = {
value: 0,
add: function(n) { this.value += n; return this; },
multiply: function(n) { this.value *= n; return this; },
get: function() { return this.value; }
};
console.log(Calculator.add(5).multiply(2).get()); // 10
class ChainCalc {
constructor(val = 0) { this.value = val; }
add(n) { this.value += n; return this; }
mul(n) { this.value *= n; return this; }
sub(n) { this.value -= n; return this; }
result() { return this.value; }
}
console.log(new ChainCalc(10).add(5).mul(2).sub(3).result()); // 27
function f(val) {
return {
add: function(n) { return f(val + n); },
mul: function(n) { return f(val * n); },
val: function() { return val; }
};
}
console.log(f(1).add(2).mul(3).val()); // 9
| 特性 | 方法鏈 | 原型鏈 |
|---|---|---|
| 本質 | 調用模式:返回對象繼續調用 | 繼承機制:對象通過 __proto__ 查找屬性 |
| 關鍵字 | return this | prototype / __proto__ |
| 目的 | API 流暢性、代碼簡潔 | 屬性/方法共享、繼承 |
| 例子 | jQuery, Lodash, Moment.js | 所有 JS 對象繼承 |
this (或新實例)。.val(), .get()) 返回實際結果,打破鏈。this 類型 (this: this) 保持類型推導。