我知道javascript原型繼承相當不錯,但我有一個類似於角scopes
的情況,我不知道如何處理它。正確的方法來更改對象__proto__屬性
讓我們開始錯誤(因爲它是壞主意改變__proto__
財產),但工作例如
https://jsfiddle.net/hxm61r7j/
function Scope() {
}
Scope.prototype.$new = function() {
var new_scope = new Scope();
//TODO: change line bellow
new_scope.__proto__ = this;
return new_scope;
}
// Create root scope
var scope_level_1 = new Scope();
scope_level_1.a = 'scope_level_1 a';
scope_level_1.b = 'scope_level_1 b';
// Create scope which inherits from parent
var scope_level_2 = scope_level_1.$new();
scope_level_2.b = 'scope_level_2 b';
// We don't have property "a" in "scope_level_2" so it will be taken from "scope_level_1"
// But we have property "b" in "scope_level_2" so it will be taken from there
console.log(scope_level_2.a, scope_level_2.b);
正如你看到的,我需要一種方法來創建某種scope
這將有一些屬性。後來我需要創建其他的scope
,它將繼承前一個。我的意思是,如果屬性沒有在當前範圍中定義,則將從父項中取出。
但我不知道如何改變這一行:new_scope.__proto__ = this;
可能重複(http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) –
@RobertRossmann這不是這種情況。我知道如何在平常情況下使用'prototype'。例如,如果我需要構造函數'Vehicle'和另外兩個構造函數'Car'和'Motorbike'並且它們都從'Vehicle'繼承。但是在這種情況下,我只需要一個繼承自它的構造函數'Scope' –
繼承自身並不會幫助實現任何內容 - 存在於Scope上的任何屬性將立即在當前對象上解析,其他所有內容都將無法解析(即'未定義「);在最壞的情況下,引擎會在遞歸查找您的財產時達到最大堆棧跟蹤。你的這種行爲的用例是什麼......? –