2016-12-13 JavaScript 中几种不同的基于 prototype 继承方式的区别
JavaScript 中几种不同的基于 prototype 继承方式的区别
普通属性的继承
第一种方式
function Employee1 (name, dept) {
console.log('Employee constructor')
this.name = name || "";
this.dept = dept || "general";
this.work = function() {console.log("Employee.work")}
this.workAsEmployee = function() { this.work() }
}
function WorkerBee1 (projs) {
console.log('WorkerBee constructor')
this.projects = projs || [];
this.work = function() {console.log("WorkerBee.work")}
this.workAsBee = function() { this.work() }
}
WorkerBee1.prototype = new Employee1;
function Engineer1 (mach) {
console.log('Engineer constructor')
this.dept = "engineering";
this.machine = mach || "";
this.work = function() {console.log("Engineer.work")}
this.workAsEngineer = function() { this.work() }
}
Engineer1.prototype = new WorkerBee1;
e1 = new Engineer1()
e1.work()
console.log(Employee1.prototype.isPrototypeOf(e1))
console.log(WorkerBee1.prototype.isPrototypeOf(e1))
console.log(e1)第二种方式
对于定义在 prototype 里面的方法呢
第一种方式改进
第二种方式的改进
要执行所有构造函数
利用 super 变量
super 变量类似,但是用 Parent.apply 方法
Parent.apply 方法最后更新于