gpt4 book ai didi

javascript - 在 JavaScript 中,如何使用单个 ".prototype" block 从子类中继承父类?

转载 作者:行者123 更新时间:2023-11-28 02:03:09 25 4
gpt4 key购买 nike

例如:

function Person() {
//person properties
this.name = "my name";
}

Person.prototype = {
//person methods
sayHello: function() {
console.log("Hello, I am a person.");
}

sayGoodbye: function() {
console.log("Goodbye");
}
}

function Student() {
//student specific properties
this.studentId = 0;
}

Student.prototype = {
//I need Student to inherit from Person
//i.e. the equivalent of
//Student.prototype = new Person();
//Student.prototype.constructor = Person;

//student specific methods
//override sayHello
sayHello: function() {
console.log("Hello, I am a student.");
}
}

我知道我可以使用以下方法实现此目的:

function Student() {
this.studentId = 0;
}

Student.prototype = new Person();
Student.prototype.constructor = Person;
Student.prototype.sayHello = function () {
console.log("Hello, I am a student.");
}

但我想继续使用第一个示例中的样式,并在可能的情况下将所有类方法定义在单个“.prototype” block 中。

最佳答案

看看 StackOverflow 上的以下答案:https://stackoverflow.com/a/17893663/783743

这个答案引入了原型(prototype)类同构的概念。简而言之,原型(prototype)对象可以用来对类进行建模。以下代码摘自上述答案:

function CLASS(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}

使用上面的方法我们可以实现 Person 如下:

var Person = CLASS({
constructor: function () {
this.name = "my name";
},
sayHello: function () {
console.log("Hello, I am a person.");
},
sayGoodbye: function () {
console.log("Goodbye");
}
});

然而,继承需要一些额外的工作。因此,让我们稍微修改一下 CLASS 函数:

function CLASS(prototype, base) {
switch (typeof base) {
case "function": base = base.prototype;
case "object": prototype = Object.create(base, descriptorOf(prototype));
}

var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}

我们还需要定义 descriptorOf 函数以使 CLASS 正常工作:

function descriptorOf(object) {
return Object.keys(object).reduce(function (descriptor, key) {
descriptor[key] = Object.getOwnPropertyDescriptor(object, key);
return descriptor;
}, {});
}

现在我们可以创建Student,如下所示:

var Student = CLASS({
constructor: function () {
this.studentId = 0;
},
sayHello: function () {
console.log("Hello, I am a student.");
}
}, Person);

亲自观看演示:http://jsfiddle.net/CaDu2/

如果您需要任何帮助来理解代码,请随时与我联系。

关于javascript - 在 JavaScript 中,如何使用单个 ".prototype" block 从子类中继承父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167133/

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