gpt4 book ai didi

javascript - 在构造函数中使用 'this' 关键字是否会增加总体内存使用量?

转载 作者:行者123 更新时间:2023-12-03 00:01:50 26 4
gpt4 key购买 nike

例如:

function Constructor() {
this.peoperty = 1;
this.myMethod1 = function() {
//do something
};
this.myMethod2 = function() {
let a = myMethod3();
}

/*no 'this' keyword for myFunction3,because
I am not going to call myFunction3 anywhere else,
except inside this particular Constructor*/
myMethod3 = function() {
let b = 0;
return b;
};
}

var hello = new Constructor();

我假设 this 关键字是指使用 new 关键字创建变量时的实例。

问题是,如果myMethod3只会在该构造函数内调用,我可以使用this myMethod3 的 > 关键字,因为我不会在代码中的任何地方使用 hello.myMethod3。这是否会在运行时节省一些内存,因为我猜只有与 this 关键字绑定(bind)的属性/方法才会占用使用 new 关键字创建的每个实例的内存空间?

最佳答案

是的,你的猜测是正确的,如果你在构造函数中声明一个方法,每个实例都会有自己的定义:

function Cat() {
this.meow = function() {
console.log('meow');
}
}

const cat1 = new Cat();
const cat2 = new Cat();

cat1.meow();
cat2.meow();

console.log(cat1.meow === cat2.meow);

如果您使用prototype关键字,则不会发生同样的情况。在这种情况下,两个对象将有一个指向相同定义的指针:

    function Cat() {
}

Cat.prototype.meow = function() {
console.log('meow');
}

const cat1 = new Cat();
const cat2 = new Cat();

cat1.meow();
cat2.meow();

console.log(cat1.__proto__.meow === cat2.__proto__.meow);

关于javascript - 在构造函数中使用 'this' 关键字是否会增加总体内存使用量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55282098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com