JS中的构造函数是JS面向对象编程的核心,虽然ES6已经引入了Class类的概念,但是论灵活性还是构造函数更胜一筹。
一段代码,先对构造函数有基本的认识:
function Animal(name, type) {
this.name = name;
this.type = type;
this.do = '';
this.action = function () {
switch (this.type) {
case 'cat':
this.do = 'climb';
break;
case 'dog':
this.do = 'fight';
break;
}
return this.do;
}
}
var animal = new Animal('老虎','cat');
console.log(animal.action()); //climb
表达式new,我总结出有以下四个步骤:
- 在构造函数中创建一个空对象。
- 将构造函数中的this指向该对象。
- 执行构造函数中的代码语句。
- 将填充完属性和方法的对象return。
每一个构造函数在被创建的时候,都会自动生成一个prototype属性,该属性是一个空对象,也就是该构造函数的原型。
接着上面的代码:
console.log(Animal.prototype === animal.__proto__); //true
当构造函数的实例需要一个属性时,会顺着__proto__属性向上查找构造函数的原型。
Animal.prototype.age = 10;
console.log(animal.age); //10
console.log(animal.__proto__.age); //10
建议:在创建构造函数时,将属性定义在函数中,方法定义在原型中。
构造函数的继承:
function A(name) {
this.name = name;
}
A.prototype = {
'getName': function () {
return this.name;
}
}
function B(name, age) {
A.call(this, name); //继承父类属性
this.age = age;
}
B.prototype = new A(); //继承父类方法
B.prototype.constructor = B; //修复构造函数指向
B.prototype.getAge = function () {
return this.age;
}
var b = new B('B', 19);
console.log(b.name); //B
console.log(b.age); //19
console.log(b.getName()); //B
console.log(b.getAge()); //19