JS 高级
这里介绍前端各种源码。
常用的定义 JS 类的方法
主要有构造函数原型
和对象创建
两种方法。原型法是通用老方法,对象创建是ES5推荐使用的方法.目前来看,原型法更普遍。
- 构造函数方法定义类
function Person(){
this.name = 'michaelqin';
}
Person.prototype.sayName = function(){
alert(this.name);
}
var person = new Person();
person.sayName();
- 对象创建方法定义类
var Person = {
name: 'michaelqin',
sayName: function(){ alert(this.name); }
};
var person = Object.create(Person);
person.sayName();
JS 类继承的方法有哪些
原型链法,属性复制法和构造器应用法. 另外,由于每个对象可以是一个类,这些方法也可以用于对象类的继承。
- 原型链法
function Animal() {
this.name = 'animal';
}
Animal.prototype.sayName = function(){
alert(this.name);
};
function Person() {}
Person.prototype = Animal.prototype; // 人继承自动物
Person.prototype.constructor = 'Person'; // 更新构造函数为人
- 属性复制法
function Animal() {
this.name = 'animal';
}
Animal.prototype.sayName = function() {
alert(this.name);
};
function Person() {}
for(prop in Animal.prototype) {
Person.prototype[prop] = Animal.prototype[prop];
} // 复制动物的所有属性到人量边
Person.prototype.constructor = 'Person'; // 更新构造函数为人
- 构造器法
function Animal() {
this.name = 'animal';
}
Animal.prototype.sayName = function() {
alert(this.name);
};
function Person() {
Animal.call(this); // apply, call, bind方法都可以.细微区别,后面会提到.
}
JS 类的多重继承的实现方法
就是类继承里边的属性复制法来实现.因为当所有父类的prototype属性被复制后,子类自然拥有类似行为和属性。