js 创建类和继承的几种方法

在面向对象编程中,类(class)是对象(object)的模板,定义了同一组对象(又称"实例")共有的属性和方法。JavaScript语言里是没有类的概念的,但是我们通过以下方法也可以模拟出类。

一.创建类:

1. 利用function关键字:

  

function Animal(name,age){
    this.name=name;
    this.age = age;
    this.getName = function(){
        return this.name;
    }
    this.setName = function(name){
        this.name = name
    }
}

var ani = new Animal('大毛',1);

原型方法:

function Animal(name,age){
    this.name=name;
    this.age = age;
}

Animal.prototype={
   getName: function(){
        return this.name;
    }
   setName: function(name){
        this.name = name
    }  
}

2.利用Object.create()方法构造:

为了解决"构造函数法"的缺点,更方便地生成对象,Javascript的国际标准ECMAScript第五版(目前通行的是第三版),提出了一个新的方法Object.create()

var Animal ={
    name: '大毛',
    getName: function(){
        return this.name;
    }
}

var ani = Object.create(Animal);
ani.getName();//大毛

对于IE9以下浏览器不支持这种写法,我们可以做以下兼容:

function classFactory(o){
    var fn = function(){}
    fn.prototype = o;
    return new fn();
}

二.继承:

1.利用prototype关键字

function extend(Sub,Sup) {
    //Sub表示子类,Sup表示超类
    // 首先定义一个空函数
    var F = function(){};
 
    // 设置空函数的原型为超类的原型
    F.prototype = Sup.prototype; 
 
// 实例化空函数,并把超类原型引用传递给子类
    Sub.prototype = new F();
 
    // 重置子类原型的构造器为子类自身
    Sub.prototype.constructor = Sub;
 
    // 在子类中保存超类的原型,避免子类与超类耦合
    Sub.sup = Sup.prototype;
 
    if(Sup.prototype.constructor === Object.prototype.constructor) {
        // 检测超类原型的构造器是否为原型自身
        Sup.prototype.constructor = Sup;
    }
 
}

2.call和apply

原文地址:https://www.cnblogs.com/freefish12/p/5578880.html