gpt4 book ai didi

javascript - JS中的继承 : this. base = Class(); this.base() 还是……?

转载 作者:数据小太阳 更新时间:2023-10-29 04:31:30 28 4
gpt4 key购买 nike

我试图在 JS 中“获得”继承。我刚刚发现了一种基本上可以将所有属性从一个对象复制到另一个对象的简洁方法:

function Person(name){
this.name="Mr or Miss: "+name;

this.introduce = function(){
console.log("Hi, I am "+this.name);
}
}

function Employee(name,title){
this.title=title;

this.base=Person;
this.base(name);

}

e = new Employee('tony', 'manager')
e.introduce();

请注意,我有一个带有构造函数的 Person() 类,它的属性“name”是由构造函数生成的。这样做的好处还在于 employee 在构造函数中也有这个名字——瞧,它使用相同的参数创建了 Person 对象。

如果我使用“原型(prototype)”方式完成此操作:

function Person(name){

this.introduce = function(){
console.log("Hi, I am "+this.name);
}
}

function Employee(name, title){
this.name = name; /* ?!?!?!?!? I can't call the proper constructor here */
this.title = title;
}
Employee.prototype= new Person(); /* ?!?!? NO NAME HERE..>? */
Employee.prototype.constructor = Employee;


e = new Employee('tony', 'manager')
e.introduce();

呃……现在怎么办?我什至无法完成这个:无法使用正确的 Person 构造函数设置 Employee 中的 this.name; Person 对象的创建在继承过程中只发生一次。

那么……我错过了什么?在我的案例中,我给出的第一个例子是“the”方式吗?有没有办法得到与第二个示例相同的结果?

帮助!

最佳答案

这种原型(prototype)继承往往是这样进行的:

function Parent() {}

function Child() {
Parent.call(this); // call the constructor of the parent
}

var Constr = function() {};
Constr.prototype = Parent.prototype;

Child.prototype = new Constr();
Child.prototype.constructor = Child;

所以“技巧”是分配 Parent.prototype作为空函数的原型(prototype)并将此函数的新实例设置为 Child 的原型(prototype).

这样做是为了扩展 Child.prototype不扩展 Parent.prototype .

您还必须在子构造函数中调用父构造函数。我想这是你挣扎的部分。每个函数都有一个 call [docs] apply [docs]让您显式设置元素 this 的方法应该在函数内部引用。

在您的示例中,它看起来像:

function Employee(name,title){
this.title=title;

Person.call(this, name);
}

没有将构造函数分配给实例的属性。

在您的示例中,this.base(name)有效,因为通过将构造函数分配给实例的属性(并以这种方式调用它),this函数内部引用该实例。


有几个库实现了这种模式,例如Google Closure library :

goog.inherits = function(childCtor, parentCtor) {
/** @constructor */
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
};

关于javascript - JS中的继承 : this. base = Class(); this.base() 还是……?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6583353/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com