开发者

variable defined in prototype are shared accross objects?

开发者 https://www.devze.com 2023-01-21 19:29 出处:网络
I have create object lik e this testObj.prototype = { cVar: 15, init: function(c){ 开发者_如何学C/*initialization code*/

I have create object lik

e this
testObj.prototype = {
    cVar: 15,
    init: function(c){
     开发者_如何学C   /*initialization code*/
        this.cVar = c;
    }
};

var a = new testObj(10);
var b = new testObj(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;
0

精彩评论

暂无评论...
验证码 换一张
取 消