我很擅长使用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();
Run Code Online (Sandbox Code Playgroud)
生成这个(模拟Web工具中的输出):
Object {test: function, test: function}
test: function (){
__proto__: Object
test: function (){
__proto__: Object
Parent
Child
Run Code Online (Sandbox Code Playgroud)
所以你看到它不是设置原型而只是"__proto__",我认为它在使用时不鼓励.您可以看到,在我的代码中,我能够正确地继承并调用父对象,但只能使用"__proto__".使用"原型"会导致错误(未定义).
这里发生了什么?我认为object.create会设置"原型",因为这是标准(或者我假设).为什么要填充并让我使用"__proto__"