简体   繁体   English

JavaScript类实例是否克隆函数?

[英]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? 当代码运行时( console.log()部分),是否在运行一个方法ret()或三个? 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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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