JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Js面向对象(oop)之继承

2017. 05. 27    

JS面向对象(OOP)之继承

function Person(name, age, sex){
	this.name = name;
	this.age = age;
	this.sex = sex;
	this.type = '人类';
	this.love = 'play';
}
通过apply实现继承
function Student(){
	Person.apply(this, arguments)
	this.love = '学习'
}
var zheng = new Student()
console.log(zheng.type)//人类
console.log(zheng)//Person{name: undefined, age: undefined, sex: undefined, type: "人类", love: "学习"}

prototype模式
function Person(){
	this.type = '人类';
	this.love = 'play';
}
Person.prototype.hobby = function(){
	alert(this.love)
}

Student.prototype = new Person()
alert(Student.prototype.constructor == Person);//true
alert(Student.prototype.constructor == Student);//false

这里体现了使用constructor判断数据类型是不稳定的,因为重写了prototype之后,原有的 constructor 引用会丢失,constructor 会默认为 Object

所以需要些以下一条代码

Student.prototype.constructor = Student;

以这种方式重设 constructor 属性会导致它的[[Enumerable]]特性被设置为 true。

[[Enumerable]]:表示能否通过 for-in 循环返回属性

alert(Student.prototype.constructor == Student);//true
var zheng = new Student()
console.log(zheng.type) //人类
console.log(zheng.love) //play
for( item in zheng){
	console.log(item)
}
//love
//type
//constructor   因为设置了 Student.prototype.constructor = Student;
//hobby