例如:
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”块中。
答案 0 :(得分:1)
在StackOverflow上查看以下答案:https://stackoverflow.com/a/17893663/783743
这个答案介绍了原型级同构的概念。简而言之,原型对象可以用来模拟一个类。以下代码取自上述答案:
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/
如果您需要任何帮助来理解代码,请随时与我联系。