我知道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上的任何属性将立即在当前对象上解析,其他所有内容都将无法解析(即'未定义“);在最坏的情况下,引擎会在递归查找您的财产时达到最大堆栈跟踪。你的这种行为的用例是什么......? –