js之改变原型对象

本文探讨了JavaScript中构造函数的内存优化技巧,通过将共享方法放置在原型对象上,避免了每次实例化时的重复,同时调整了getArea属性的可枚举性,确保了代码的高效运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function Rectangle(width, height){
    this.width = width;
    this.height = height;
    this.getArea = function(){
        return '矩形的面积为' + (width * height);
    }
}

var rect1 = new Rectangle(40, 20);
var rect2 = new Rectangle(50, 20);
var rect3 = new Rectangle(60, 20);
console.log(rect1.getArea());
console.log(rect2.getArea());
console.log(rect3.getArea());

如上代码,每次实例化出一个对象,都会添加getArea这个属性,它是三个对象共有且不变的,因此将getArea放在构造函数中就会在创建对象时被多次添加,浪费内存!

 

因此我们将getArea属性添加到原型对象上就减少了多次添加,实例化对象会沿着原型链查找到此属性

实现了共享该属性:

function Rectangle(width, height){
    this.width = width;
    this.height = height;
}

/* 
    将此getArea属性定义在构造函数的原型对象中,就不会被重复添加了
    实例化对象会沿着原型链查找到此属性
*/
Rectangle.prototype.getArea = function(){
    return '矩形的面积为' + (this.width * this.height);
}
var rect1 = new Rectangle(40, 20);
var rect2 = new Rectangle(50, 20);
var rect3 = new Rectangle(60, 20);
console.log(rect1.getArea());
console.log(rect2.getArea());
console.log(rect3.getArea());
console.log(rect1);
// 但是添加到原型对象上的getArea属性的特性是可遍历的,所有使用in遍历时,会被遍历出
for(var key in rect1){
    console.log(key);   // width, height, getArea
}

// 所以更改属性设置
Object.defineProperty(Rectangle.prototype, 'getArea', {
    enumerable: false,
    writable: false,
    configurable: false
});

for(var key in rect1){
    console.log(key);   // width, height
}

 

第二种添加到原型对象上的方式:

// 第二种方式
function Rectangle(width, height){
    this.width = width;
    this.height = height;
}

// 直接替换原型对象,但是要记得添加上构造函数属性
Rectangle.prototype = {
    constructor: Rectangle,
    getArea: function(){
        return '矩形的面积为' + (this.width * this.height);
    }
}

// 修改特性
Object.defineProperties(Rectangle.prototype, {
    constructor: {
        enumerable: false,
        configurable: false,
        writable: false
    },
    getArea: {
        enumerable: false,
        configurable: false,
        writable: false
    }
})

var rect1 = new Rectangle(40, 20);
var rect2 = new Rectangle(50, 20);
var rect3 = new Rectangle(60, 20);
console.log(rect1.getArea());
console.log(rect2.getArea());
console.log(rect3.getArea());
console.log(rect1);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值