0

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

我有一个 Person 类,我从(John 和 Suzie)创建了 2 个实例。现在,我想创建另一个基于 Person 的类(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);
4

3 回答 3

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();
于 2013-09-23T21:51:30.897 回答
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(...);
于 2013-09-23T21:52:29.763 回答
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
于 2013-09-23T21:59:09.407 回答