Discuss
/
JavaScript
/
廖老师一个问题
廖老师一个问题
Topic sourceCodecademy上讲解的貌似就是这样:
PrimaryStudent.prototype = new Student();
PrimaryStudent.prototype.constructor = PrimaryStudent;
试了一下,确实是可以的,不过在new Student()
的时候要传入参数,比如传入空字符串。
'use strict';
function Student(props) {
this.name = props.name || 'Unnamed';
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
function PrimaryStudent(props) {
Student.call(this, props);
this.grade = props.grade || 1;
}
// 实现原型继承链:
PrimaryStudent.prototype = new Student('');
PrimaryStudent.prototype.constructor = PrimaryStudent;
// 绑定其他方法到PrimaryStudent原型:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
var xiaoming = new PrimaryStudent({
name: '小明',
grade: 2
});
alert(xiaoming.name); // '小明'
alert(xiaoming.grade); // 2
// 验证原型:
alert(xiaoming.__proto__ === PrimaryStudent.prototype); // true
alert(xiaoming.__proto__.__proto__ === Student.prototype); // true
// 验证继承关系:
alert(xiaoming instanceof PrimaryStudent); // true
alert(xiaoming instanceof Student); // true
关键区别应该是采用这种继承:
PrimaryStudent.prototype = new Student();
PrimaryStudent.prototype.constructor = PrimaryStudent;
会使PrimaryStudent.prototype
在new Student()
时获得Student()
里this
的属性和方法。
而把PrimaryStudent.prototype = new Student();
换为
var F = function () {};
F.prototype = Student().prototype;
PrimaryStudent.prototype = new F();
因为F
为空函数,此时PrimaryStudent.prototype
不会带上多余属性。
考虑到在原型继承时我们只希望让PrimaryStudent.prototype
老老实实做个原型,所以就减少开销和保证原型继承顺利来说,采用道叔的方法更好。
同时如楼上所说,用中间函数我们也不用考虑给Student()
传参数的问题。
- 1
佳喵喵喵喵将军
看明白了,可是有个问题
为什么要
new F()
,直接new一个student,然后改变这个new student的constructor
和PrimaryStudent.proto
不就可以了么?