简体   繁体   中英

Do JavaScript class instances clone functions?

If i have the following code:

function myClass(){
    this.type = 1;
    this.ret = function(){
        return this.type;
    }
}

var ins1 = new myClass,
    ins2 = new myClass,
    ins3 = new myClass;

ins2.type = 2;
ins3.type = 3;

console.log(ins1.ret() + ' - ' + ins2.ret() + ' - ' + ins3.ret());

The output in the console is

1 - 2 - 3

When the code runs (the console.log() part), is there one method ret() running, or three? If each instance creates a new method, how can I avoid that? If they all do the same exact thing, why have three of them.

The methods are different indeed. You are wasting memory.

ins1.ret == ins2.ret; // false

Instead, you can define the method in the prototype:

function myClass(){}
myClass.prototype.type = 1;
myClass.prototype.ret = function(){
  return this.type;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM