Discuss / JavaScript / 廖老师一个问题

廖老师一个问题

Topic source

看明白了,可是有个问题

为什么要new F(),直接new一个student,然后改变这个new student的constructorPrimaryStudent.proto不就可以了么?

Codecademy上讲解的貌似就是这样:

PrimaryStudent.prototype = new Student();
PrimaryStudent.prototype.constructor = PrimaryStudent;

雨巷之约

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

试了一下,确实是可以的,不过在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

LevonLin

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

关键区别应该是采用这种继承:

PrimaryStudent.prototype = new Student();
PrimaryStudent.prototype.constructor = PrimaryStudent;

会使PrimaryStudent.prototypenew Student()时获得Student()this的属性和方法。

而把PrimaryStudent.prototype = new Student();换为

var F = function () {};
F.prototype = Student().prototype;
PrimaryStudent.prototype = new F();

因为F为空函数,此时PrimaryStudent.prototype不会带上多余属性。

考虑到在原型继承时我们只希望让PrimaryStudent.prototype老老实实做个原型,所以就减少开销和保证原型继承顺利来说,采用道叔的方法更好。

同时如楼上所说,用中间函数我们也不用考虑给Student()传参数的问题。

Glimmer

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

原来是这样子,谢谢


  • 1

Reply