JavaScript 字段继承奇怪的行为

标签 javascript oop

function A(){
    this.a = {};
    this.b = 0;
    this.Test = function(value){
        this.a.x = value;
        this.b = value;
    };
}

function B(){}
B.prototype = new A;


    var b1= (new B());
    b1.Test(1);
    var b2= (new B());
    b2.Test(2);
    log(b1.b == 1); //true
    log(b2.b == 2); //true
    log(b1.a.x == 1);//false x == 2
    log(b2.a.x == 2);//true

为什么实例共享字段a?

最佳答案

发生这种情况是因为 a 对象在 B 的所有实例之间共享(因为 B 原型(prototype)是 A 的实例)。

解决方法是在您的 Test 方法中分配一个新对象作为自己的属性隐藏原型(prototype)链上可用的对象,例如:

function A(){
  this.a = {};
  this.b = 0;
  this.Test = function(value){
    this.a = {x: value}; // shadow the object on the prototype chain
    this.b = value;
  };
}

function B(){}
B.prototype = new A;


var b1= new B();
b1.Test(1);

var b2= new B();
b2.Test(2);

console.log(b1.b == 1); //true
console.log(b2.b == 2); //true
console.log(b1.a.x == 1);//true
console.log(b2.a.x == 2);//true

关于JavaScript 字段继承奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3495648/

相关文章:

javascript - 获取背景图片url值

javascript - 访问网页后尝试查找任何元素时 Watir 超时

javascript - 为什么回调未定义?

perl - 即使子类覆盖该属性,也会默认使用 Moose 属性

Java hangman 帮助,包括我的代码

javascript - 如何在 javascript 闭包中将 'this' 保留在类中

javascript 音频每次点击都会获得 lauder

javascript - 在 JavaScript 中访问输入文件上传字段

php - OOP PHP新手,指导请求,类间数据共享设计

java - 如何理解码成和转发方式?