javascript 面向對象

  

一、對象

一、基於Obeject

var obj = new Object();函數

obj.name = 'eric';this

obj.age=25;prototype

obj.sex='男';對象

obj.getName = funtion(){get

  return this.name;原型

 }io

二、基於字面量

var obj = {function

  name:'eric',object

  age: 25,構造函數

  sex:'男',

  getName: function(){

    return this.name;

  }

}

二、建立對象方式

 1工廠模式

  function fun(name,age,sex){

    var obj =  new Object();

    obj.name = name;

    obj.age = age;

    obj.sex = sex;

    obj.setName = function(){

      return this.name;

    }

    return obj

  }

  fun('eric',25,'男');

 2構造函數

  function fun(name,age,sex){

    this.name = name;

    this.age = age ;

    this.sex = sex ;

    this.setName = function(){

     return this.name;

    }

  }

  var obj = new fun('eric',25,'男');  

 3原型模式

  function fun(){

  }

  fun.prototype.name = 'eric';

  fun.prototype.age = 25;

  fun.prototype.sex = '男';

  fun.prototype.getName = function(){

    return this.name;

  }

  var obj = new fun();

  var obj1 = new fun();

  obj === obj1 //false(不是同一個obj);

  obj.getName() === obj1.getName() // true (不一樣object公用一個原型對象方法)

相關文章
相關標籤/搜索