2016-08-19 18 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