2016-08-19 59 views
-2
function test() { 
    this.a = { 
     b: 4 
    }; 
} 

test.prototype.a = { 
    c: 5 
}; 

var example = new test(); 

为什么example.a.c == undefinedJavascript原型未定义而不是继承?

它不应该继承原型并返回5


如果这是不可能的,是有一些方法来添加代码返回原型?:

function test() { 
    this.a = { 
     b: 4, 
     c: *this.return.prototype* 
    }; 
} 
+1

你的原型将工作'example.a.c',除了'this.a'接管'test.prototype.a'优先。 – Barmar

+0

@Barmar,所以它不像$ .extend()和2个创建新对象的对象a = {b:4,c:5};? – seahorsepip

+1

这是正确的,原型不会递归合并。 – Barmar

回答

1

定义一个getter方法a.c访问的原型。

function test() { 
 
    this.a = { 
 
    b: 4, 
 
    get c() { 
 
     return test.prototype.a.c; 
 
    } 
 
    }; 
 
} 
 

 
test.prototype.a = { 
 
    c: 5 
 
}; 
 

 
var example = new test(); 
 
console.log(example.a.b); 
 
console.log(example.a.c); 
 
// update prototype 
 
test.prototype.a.c = 10; 
 
console.log(example.a.c);

-1

当您访问“A”,它首先找到的例子所示。如果找不到,它会尝试在示例结构的原型中找到'a'。因此它会尝试访问test.ptototype.c.So您的代码找不到examlpe.c.我认为您可以像这样更改代码。

function test() { 
    this.a = { 
     b: 4 
    }; 
} 
test.prototype.c = 5; 
var example = new test(); 
console.log(example.c);//print 5 
+1

他希望'example.a.c',而不是'example.c'。 – Barmar

2

example.a要么引用一个对象或其他的,你不能直接使检索不同对象的属性。

我会做的是使example.a从另一个继承的对象:

function test() { 
 
    this.a = Object.create(test.a_proto); 
 
    this.a.b = 4; 
 
} 
 
test.a_proto = { 
 
    c: 5 
 
}; 
 
var example = new test(); 
 
console.log(example.a.b); // 4 (own) 
 
console.log(example.a.c); // 5 (inherited)

+0

在这种情况下,如果他在创建'example'后更改'test.a_proto.c',会发生什么?它会继续使用继承的原型,还是在您调用Object.create(test.a_proto)'时创建副本? – Barmar

+0

我只是试过了,它继续从proto继承。尼斯。 – Barmar

+0

@Barmar是的,'test.a_proto'属性的变化将被继承。但是替换'test.a_proto'本身不会。 – Oriol