原型中定义的变量是否与对象共享? [英] variable defined in prototype are shared accross objects?

查看:58
本文介绍了原型中定义的变量是否与对象共享?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了对象

e this
testObj.prototype = {
    cVar: 15,
    init: function(c){
        /*initialization code*/
        this.cVar = c;
    }
};

var a = new testObj(10);
var b = new testObj(20);

现在两个对象的cVar值都是20.它们是否共享变量?我如何为每个对象获得单独的变量?

Now both object's cVar values is 20. Are they sharing the variable? How i can get seperate variable for each object?

推荐答案

是的,它们是共享的。对于单独的属性,在构造函数中定义它们:

Yes, they're shared. For separate properties, define them inside the constructor:

function Ctor() {
    this.notShared = 1;
};

Ctor.prototype.shared = 2;

这篇关于原型中定义的变量是否与对象共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆