js面向對象基礎總結

 

 js中如何定義一個類?app

定義的function就是一個構造方法也就是說是定義了一個類;用這個方法能夠new新對象出來。this

function Person(name, age){

  this.name = name;

  this.age = age;

  this.showInfo = function(){

    alert(this.name + this.age + "");

  }

}

Person p1 = new Person('小明', 17);

 類的繼承spa

咱們把具備相同屬性特徵的類放到一個父類裏,經過繼承子類一樣擁有父類的屬性和特徵。其中繼承方法有對象冒充和原型鏈繼承。prototype

對象冒充:code

function Rect(width, height){

    this.width = width;

    this.height = height;

    this.area = function(){return this.width*this.height;};

}

 

function MyRect(width, height, name){

//    this.newMethod = Rect;

//    this.newMethod(width,height);

//    delete this.newMethod;

    Rect.call(this,width,height);// Rect.apply(this, arguments);

    this.name = name;

    this.show = function(){

        alert(this.name+" with area:"+this.area());

    }

}

原型鏈(prototype chaining):對象

function Rect(){

}

Rect.prototype = {

        width:10,

        height : 10,

        area : function(){return this.width*this.height;}

};

 

function MyRect(name){

    this.name = name;

    this.show = function(){

        alert(this.name + " with area:" + this.area());

    }

}

MyRect.prototype = new Rect();
相關文章
相關標籤/搜索