动漫引擎

导航

JavaScript类继承, 用什么方法好

JavaScript类继承, 用什么方法好

 

一个实例:

基类Car:

    function Car(color, year) {

        this.name = "car";

this.color = color;

        this.year = year;

    }

 

    var p = Car.prototype;

 

    p.getName = function() {

        console.log(this.color + " " + this.name + ' ' + this.year);

    };

    

子类Audi:

    function Audi(color, year) {

        Car.call(this, color, year);

        this.name = 'Audi';

    }

 

    Audi.prototype = Object.create(Car.prototype);

    Audi.prototype.constructor = Audi;

   var p =  Audi.prototype;

    p.getName2 = function() {

        console.log("Audi");

    };

 

基类的定义

THREE.BufferGeometry = function () {

Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );

this.uuid = THREE.Math.generateUUID();

this.name = '';

this.type = 'BufferGeometry';

};

 

THREE.BufferGeometry.prototype = {

constructor: THREE.BufferGeometry,

getIndex: function () {

return this.index;

},

}

 

好处, 构造函数可以任意带参数 

 

 

1) 继承父类的函数, 有几种方法

Audi.prototype = Object.create(Car.prototype);

Audi.prototype = new Car();  // 缺陷: 开销大,适合于构造函数无参数的情形,

 

2) 调用父类的初始化函数, 在子类构造函数中,

Car.call(this, color, year);

 

3) 把构造函数也放到prototype中

Audi.prototype.constructor = Audi
(对于copy,clone之类的函数, 需要返回子类的类别, 需要设置constructor, 否则返回的类别总是基类)

posted on 2017-03-10 08:24  动漫引擎  阅读(153)  评论(0编辑  收藏  举报