如何基于现有类创建新的JavaScript类并对其进行扩展

时间:2013-09-23 21:35:01

标签: javascript constructor javascript-objects

我正在学习JavaScript,并且对于如何基于现有类创建新的JavaScript类并对其进行扩展感到困惑。

我有一个Person类,我从(John和Suzie)创建了2个实例。现在,我想创建另一个基于Person的classe(Employee),其中包含更多属性,如Employee Number(并且可以返回到John以便他继承Employee类)。

这就是我所拥有的:

var Person = function (name, age){
    this.name = name || "UNKNOWN";
    this.age= age || "UNKNOWN";
}
Person.prototype.sayHello = function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old");
};
var john = new Person("John Smith",72);
var Suzie = new Person("Suzie Brown", 25);

3 个答案:

答案 0 :(得分:0)

//create Employee
var Employee = function(name, age, ...extra parameters){
    this.name = name || "UNKNOWN";
    this.age= age || "UNKNOWN";
    //employee related stuff...
};
//extend Person
Employee.prototype = new Person();

答案 1 :(得分:0)

var Employee = function (name, age, employeeNumber) {
    ...
};

Employee.prototype = new Person();  // copies Person's name and age to Employee
Employee.prototype.employeeNumber = 0;  // or whatever defaults you want

var Bob = new Employee(...);

答案 2 :(得分:0)

将您的原型分配给父项的实例,并确保在子构造函数中调用父构造函数:

var Person = function (name, age){
    this.name = name || "UNKNOWN";
    this.age= age || "UNKNOWN";
}

Person.prototype.sayHello = function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old");
};

var Employee = function(name, age, id) {
    Person.call(this, name, age);

    this.id = id || 'UNKNOWN';
};

Employee.prototype = new Person();

Employee.prototype.getHired = function() {
    console.log('ZOMG I GOT HIRED! My ID # is:', this.id);
};

使用它的一些例子:

var bob = new Person('Bobby', 25);
console.log(bob.name); //Bobby
console.log(bob.age); //25
console.log(bob.id); //undefined
bob.sayHello(); //Hello, my name is Bobby and I am 25 years old

var suse = new Employee('Susan', 32, 1337);
console.log(suse.name); //Susan
console.log(suse.age); //32
console.log(suse.id); //1337
suse.sayHello(); //Hello, my name is Susan and I am 32 years old
suse.getHired(); //ZOMG I GOT HIRED! My ID # is: 1337