ES5的继承
1. 利用构造函数创建对象
// 构造函数
function Obj(uname, age) {
// 属性
this.uname = uname;
this.age = age;
// 方法
this.method = function() {
console.log('对象的方法');
}
}
// 创建实例对象
var test = new Obj('uname', 18);
// 使用方法
test.method();
//
Obj.sex = 'boy'
构造函数名字的首字母要大写,且与new一起使用
- 静态成员和实例成员:
构造函数中的属性方法被叫做成员。其中:
(1)静态成员:在构造函数本身上添加的成员,如sex,静态成员只能通过构造函数来访问;
(2)实例成员:在构造函数内部通过this添加的,如uname、age、method,只能通过实例化的对象来访问;
2. 构造函数原型 prototype
每一个构造函数中都有一个prototype原型对象,把不变的方法直接定义在prototype对象上,所有的实例对象就可以共享这些方法。
实例对象在构造时,本身会有一个__proto__属性指向prototype原型对象,这样构造的实例对象就可以使用prototype创建的方法了。
// 构造函数
function Obj(uname, age) {
// 属性
this.uname = uname;
this.age = age;
// 方法
}
Obj.prototype.method = function() {
console.log('用原型对象创建的方法');
}
Obj.prototype.sex = 'boy'
// 创建实例对象
var test1 = new Obj('uname', 18);
var test2 = new Obj('uname', 19);
// 验证两个实例对象的存储空间是一致的
console.log(test1.__proto__===Obj.prototype);
// return true
console.log(test1.method()===test2.method());
// return true
3. constructor构造函数
实例对象原型__proto__和构造函数原型对象prototype中都有constructor属性,称为构造函数,因为他指回构造函数本身。它主要用来记录该对象引用哪个构造函数,可以让原型对象指向原来的构造函数。
// 构造函数
function Obj(uname, age) {
// 属性
this.uname = uname;
this.age = age;
// 方法
}
// 若以对象的方式创建方法,原来的constructor将会被覆盖掉,因此需要用constructor指回构造函数(constructor: Obj,)
Obj.prototype = {
constructor: Obj,
method1: function() {
console.log('方法1');
},
method2: function() {
console.log('方法2');
}
}
// 创建实例对象
var test = new Obj('uname', 18);
// 验证是否指回Obj
console.log(Obj.prototype.constructor);
console.log(test.__proto__.constructor);
4. 继承
- call (obj, 参数1,参数2,…)可以更改函数的this指向
- 继承父类属性
function Father(uname, age) {
this.uname = uanme
this.age = age
}
function Son(uname, age, score) {
// 继承父类属性
Father.call(this, uname, age)
this.score = score
}
- 继承父类方法
function Father(uname, age) {
this.uname = uanme
this.age = age
}
Father.prototype.money = function() {
console.log('100');
}
function Son(uname, age, score) {
Father.call(this, uname, age)
this.score = score
}
// 继承父类方法
Son.prototype = new Father();
Son.prototype.constructor = Son;
ES6的继承
1. 创建类
- 类中不需要写function,不同的方法之间不需要“, ”分割。
// 创建Obj类
class Obj {
// 构造函数
constructor(uname, age) {
this.uname = uname;
this.age = age;
}
// 添加方法
method() {
console.log('方法');
}
}
// 利用类创建对象
var test = new Obj('name', 18);
2. 继承
- super ( ) 可以访问和调用对象父类上的函数;
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
// 添加父类的方法
father_method() {
console.log('父类的方法');
}
father_sum() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x, y) {
// 必须在子类this之前调用super
super(x, y);
this.x = x;
this.y = y;
}
// 用super关键字调用父类的普通方法
son_method() {
console.log('子类调用的' + super.father_method());
}
}
// 利用类创建对象
var son = new Son(1, 2);
son.father_method();
son.sum();
son.son_method();
注意:
类中没有变量提升,因此必须先定义类,再进行实例化
constructor中的this指向的是实例对象,方法中的this指向的是调用者