使用 object.create 设置 object 的原型
set an object's prototype using object.create
在下面的代码中,如何使用 object.create() method.I 将 child 的原型设置为 parent method.I
child.prototype=new Parent();
但我想使用 object.create
来实现。使用 child.prototype=Object.create(Parent) 没有将原型设置为 Parent
function Parent() {
this.parentFunction = function(){
console.log('parentFunction');
}
}
Parent.prototype.constructor = Parent;
function Child() {
this.parentFunction = function() {
this.constructor.prototype.parentFunction.call(this);
console.log('parentFunction from child');
}
}
Child.prototype = Object.create(Parent);
Child.prototype.constructor = Child;
var child = new Child();
console.dir(child);
child.parentFunction();
两期:
您定义的第一个parentFunction
是在Parent
的构造函数中,不是原型。所以 Parent.prototype.parentFunction
没有定义。相反,对于 Parent
.
的每个实例,都有一个单独的 parentFunction
副本
在Child
构造函数中,this.constructor.prototype
指的是Child
的原型,不是Parent
的原型。如果您想要 Parent
原型,可以使用 this.prototype.prototype
.
访问
我对您的代码进行了最低限度的修改,以便对子项调用 parentFunction
对父项调用 parentFunction
:
function Parent() {
}
Parent.prototype.parentFunction = function(){
console.log('parentFunction in parent');
}
Parent.prototype.constructor = Parent;
function Child() {
}
Child.prototype = Object.create(Parent);
Child.prototype.parentFunction = function() {
this.prototype.parentFunction.call();
console.log('parentFunction from child');
};
Child.prototype.constructor = Child;
var child = new Child();
console.dir(child);
child.parentFunction();
child.prototype=new Parent();
但我想使用 object.create
来实现。使用 child.prototype=Object.create(Parent) 没有将原型设置为 Parent
function Parent() {
this.parentFunction = function(){
console.log('parentFunction');
}
}
Parent.prototype.constructor = Parent;
function Child() {
this.parentFunction = function() {
this.constructor.prototype.parentFunction.call(this);
console.log('parentFunction from child');
}
}
Child.prototype = Object.create(Parent);
Child.prototype.constructor = Child;
var child = new Child();
console.dir(child);
child.parentFunction();
两期:
您定义的第一个
parentFunction
是在Parent
的构造函数中,不是原型。所以Parent.prototype.parentFunction
没有定义。相反,对于Parent
. 的每个实例,都有一个单独的 在
Child
构造函数中,this.constructor.prototype
指的是Child
的原型,不是Parent
的原型。如果您想要Parent
原型,可以使用this.prototype.prototype
. 访问
parentFunction
副本
我对您的代码进行了最低限度的修改,以便对子项调用 parentFunction
对父项调用 parentFunction
:
function Parent() {
}
Parent.prototype.parentFunction = function(){
console.log('parentFunction in parent');
}
Parent.prototype.constructor = Parent;
function Child() {
}
Child.prototype = Object.create(Parent);
Child.prototype.parentFunction = function() {
this.prototype.parentFunction.call();
console.log('parentFunction from child');
};
Child.prototype.constructor = Child;
var child = new Child();
console.dir(child);
child.parentFunction();