js实现扩展
使用原型链扩展
在JavaScript中,可以通过原型链为内置对象或自定义对象添加方法或属性。这种方法不会影响原有对象的实例,但会影响所有后续创建的实例。
Array.prototype.last = function() {
return this[this.length - 1];
};
const arr = [1, 2, 3];
console.log(arr.last()); // 输出3
使用类继承扩展
ES6的class语法可以更方便地实现继承和扩展。通过extends关键字可以创建子类,继承父类的特性并添加新的方法或属性。
class ExtendedArray extends Array {
last() {
return this[this.length - 1];
}
}
const extendedArr = new ExtendedArray(1, 2, 3);
console.log(extendedArr.last()); // 输出3
使用对象组合扩展
对象组合是一种更灵活的扩展方式,通过将多个对象组合在一起形成新对象,而不是通过继承。
const arrayUtils = {
last: function() {
return this[this.length - 1];
}
};
const arr = [1, 2, 3];
Object.assign(arr, arrayUtils);
console.log(arr.last()); // 输出3
使用装饰器模式扩展
装饰器模式允许在不修改原有对象的基础上动态添加功能。在JavaScript中可以通过高阶函数实现装饰器。
function withLast(array) {
array.last = function() {
return this[this.length - 1];
};
return array;
}
const arr = withLast([1, 2, 3]);
console.log(arr.last()); // 输出3
使用Proxy扩展
Proxy对象可以定义基本操作的自定义行为,如属性查找、赋值等,从而实现更灵活的扩展。
const arrayWithLast = new Proxy([1, 2, 3], {
get(target, prop) {
if (prop === 'last') {
return () => target[target.length - 1];
}
return target[prop];
}
});
console.log(arrayWithLast.last()); // 输出3
使用函数式扩展
函数式编程风格强调纯函数和不可变性,可以通过返回新对象或数组的方式实现扩展。
function addLastMethod(array) {
return {
...array,
last: () => array[array.length - 1]
};
}
const arr = addLastMethod([1, 2, 3]);
console.log(arr.last()); // 输出3






