![](https://img-blog.csdnimg.cn/20191004223813601.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3l1eHVhYw==,size_16,color_FFFFFF,t_70)
/*
Java:
1. Instance fields
2. Instance methods
3. Class fields
4. Class methods
Javascript:
1. Constructor object => class methods and class fields
2. Prototype object => instance methods
3. Instance object => instance fields
*/
// 定义Person类
function Person(pname) {
this.pname = pname;
};
Person.prototype.speak = function () {
console.log(this.pname + " is speaking...");
};
Person.prototype.walk = function () {
var ts = typeof (this).toString();
console.log(this.pname + " is walking...");
};
// 定义Student类继承自Person
function Student(pname) {
Person.call(this, pname);
};
// 修改Student的prototype
Student.prototype = Object.create(Person.prototype);
// 修改Student的prototype的constructor
Object.defineProperty(Student.prototype, 'constructor',
{
value: Student,
enumerable: false,
writable: true
});
// 增加一个方法
Student.prototype.study = function () {
var ts = typeof (this).toString();
console.log(this.pname + " is studying...");
};
var aStudent = new Student("Chris");
aStudent.speak();
aStudent.walk();
aStudent.study();
// 定义Teacher类继承自Person
function Teacher(pname) {
Person.call(this, pname);
};
Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;
Teacher.prototype.teach = function () {
var ts = typeof (this).toString();
console.log(this.pname + " is teaching...");
};
var aTeacher = new Teacher("Stella");
aTeacher.speak();
aTeacher.walk();
aTeacher.teach();
enjoy.