Discuss / JavaScript / 使用Object.create 原型继承

使用Object.create 原型继承

Topic source

ECMAScript 5 标准 参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

function Student(props) {
    this.name = props.name || 'Unnamed';
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
}
// PrimaryStudent构造函数:
function PrimaryStudent(props) {
    Student.call(this, props);
    this.grade = props.grade || 1;
}

PrimaryStudent.prototype = Object.create(Student.prototype);
PrimaryStudent.prototype.constructor = Student;

PrimaryStudent.prototype.getGrade = function () {
    return this.grade;
};

// 创建xiaoming:
var xiaoming = new PrimaryStudent({
    name: '小明',
    grade: 2
});
alert(xiaoming.name);
console.log(xiaoming.grade);

caylof

#2 Created at ... [Delete] [Delete and Lock User]

PrimaryStudent.prototype.constructor应该指向PrimaryStudent吧

PrimaryStudent.prototype.constructor = PrimaryStudent;

  • 1

Reply