我对使用 object.create 而不是经典的 js 方式来实现原型继承非常陌生。
至少在 Chrome 中,我很惊讶地看到以下代码:
var baseObject = {
test : function(){
console.log('Child');
}
}
var newObject = Object.create(baseObject);
newObject.test = function(){
console.log('Parent');
this.__proto__.test();
}
console.log(newObject);
newObject.test();
产生这个(模拟网络工具中的输出):
Object {test: function, test: function}
test: function (){
__proto__: Object
test: function (){
__proto__: Object
Parent
Child
所以你看到它没有设置原型,而只是“__proto__”,我认为不鼓励使用它。您可以在我的代码中看到,我能够正确继承并调用父对象,但只能使用“__proto__”。使用“原型”会导致错误(未定义)。
这里发生了什么?我认为 object.create 会设置“原型”,因为这是标准(或者我假设)。为什么它会填充并让我使用“__proto__”