问题:
For example:
function Constructor() {
this.peoperty = 1;
this.myMethod1 = function() {
//do something
};
this.myMethod2 = function() {
le...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
For example:
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();
I assume this
keyword refers to the instance when creating a variable use new
keyword.
The question is, if the myMethod3
will only be called inside that constructor, can I not use this
keyword for myMethod3
, because I am not going to use hello.myMethod3
anywhere in my code. Does this save some memory while running, since I guess only properties/methods that bind with a this
keyword will occupy memory spaces for each instance created with a new
keyword?
回答1:
Yes, your guess is correct, if you declare a method in the constructor, every instance will have its own definition:
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);
The same doesn't happen if you use the prototype keyword. In that case, both object will have a pointer to the same definition:
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);
回答2:
In your current code, you aren't declaring myFunction3
, therefore the function will be in the global scope, and every new instantiation of the Constructor
will override the previous myFunction3
:
const instance = new Constructor();
myFunction3 = () => alert("whoops");
instance.myFunction2(); // "whoops"
Therefore there is just one myFunction3
at a time, which saves memory, however it makes little sense to redeclare it in the constructor then (it never makes sense to not declare variables).
Under the assumption that you declared it properly with:
function myFunction3() {
let b = 0;
return b;
};
then you won't save any memory at all, as a reference to myFunction3
is kept in the closure of the other functions you assign to this
, therefore myFunction3
will have to stay as long in memory as whatever instance this
is referring to does. If you do
this.myFunction3 = function() { /*...*/ };
it will also stay in memory as long as this
exists, so they are actually equal from a memory point of view. However myFunction3
is somewhat "private" as it can't be accessed via this
.