我非常了解 javascript 原型(prototype)继承,但我遇到了类似于 Angular scope
的情况,我不知道如何处理它。
让我们从错误开始(因为更改__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);
如您所见,我需要一种方法来创建某种具有某些属性的范围
。稍后我需要创建其他范围,它将继承前一个范围。我的意思是,如果属性未在当前范围内定义,它将从父级获取。
但我不知道如何更改这一行:new_scope.__proto__ = this;
最佳答案
我认为您正在寻找 Object.create()
.
此函数允许您创建一个新的 JavaScript 对象,并将内部原型(prototype)属性 (__proto__
) 设置为您作为第一个参数传递给函数的任何对象:
Scope.prototype.$new = function() {
var new_scope = Object.create(this);
// If you also need to call the constructor function:
Scope.call(new_scope);
return new_scope;
}
或者,您可以使用Object.setPrototypeOf()
,但这是 ECMAScript 6 的一部分,浏览器支持可能会有所不同:
Scope.prototype.$new = function() {
var new_scope = new Scope();
Object.setPrototypeOf(new_scope, this);
return new_scope;
}
请注意,__proto__
属性仅在 ES 6 中标准化,因此不鼓励对其进行直接操作。
关于javascript - 更改对象 __proto__ 属性的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30575618/