JS继承

157 阅读1分钟

一:_proto_和prototype的关系  

参考:原型链

var one = {x: 1};
var two = new Object();
one.__proto__ === Object.prototype // true
two.__proto__ === Object.prototype // true
one.toString === one.__proto__.toString // true

_proto_用于实例,prototype.hasOwnProperty判断实例是否拥有属性

二:面向对象编程

function Person(name){
    this.name = name;
}

Person.prototype.say = function(){
    console.log(this.name);
};

var person = new Person();
person.say();

三:继承

参考:JS的六种继承方式

1.原型链继承:基本思想是让一个原型对象指向另一个类型的实例

function Parent(){
    this.property = true;
}
Parent.prototype.parentValue = function(){
    return this.property;
};
function Child(){
    this.childPro = false;
}
Child.prototype = new Parent();
Child.prototype.childValue = function(){
    return this.childPro;
};
var child = new Child();
console.log(child.parentValue()); //true

2.借用构造函数:在子类构造函数的内部调用父类构造函数,可以借助apply()和call()方法来改变对象的执行上下文。借用构造函数可以传递参数。

function Parent(){
    this.color = ['red','blue','green'];
}
function Child(){
    Parent.call(this);
}
var instance1 = new Child();
var instance2 = new Child();
instance1.color.push('black');
console.log(instance1.color); //['red','blue','green','black']
console.log(instance2.color); //['red','blue','green']

3.组合继承(原型链+构造函数):使用原型链实现对原型属性和方法的继承,借用构造函数实现对实例属性的继承。实现函数的复用,保证每个实例都有自己的属性。

function Parent(name){
    this.name = name;
    colors = ['red','blue','green'];
}
Parent.prototype.parentValue = function(){
    console.log(this.name);
};
function Child(name,child){
    Parent.call(this,name);
    this.child = child;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
Child.prototype.childValue = function(){
    console.log(this.child);
};

var instance = new Child('mak','big');
console.log(instance.colors); //['red','blue','green']
instance.parentValue();       //'mak'
instance.childValue();        //'big'

4.利用空对象继承

function extend(Child,Parent){
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}

5.寄生式继承:创建一个用于封装继承过程的函数

function createClone(o){
    var clone = Object.create(o); //创建一个新对象
    clone.sayHi = function(){   //添加方法
        console.log('hi');
    };
    return clone;   //返回对象
}
var person = {
    name:'bob'
};
var another = createClone(person);
another.sayHi();

6.ES6的class继承

class Point{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }
}
class ColorPoint extends Point{
    constructor(x,y,color){
        super(x,y);
        this.color = color;
    }
}

7.其他方法。。。。