js的對象建立

建立對象

  • 字面量的方式:
var myHonda = {color: "red", wheels: 4, engine: {cylinders: 4, size: 2.2}}

就是new Object()的語法糖,同樣同樣的。html

  • 工廠模式:
function createCar(){    
  var oTemp = new Object();    
  oTemp.name = arguments[0];
  //直接給對象添加屬性,每一個對象都有直接的屬性    
  oTemp.age = arguments[1];    
  oTemp.showName = function () {        
    alert(this.name);    
  };//每一個對象都有一個 showName 方法版本    
  return oTemp;
};
var myHonda = createCar('honda', 5)

只是給new Object()包了層皮,方便量產,並無本質區別,姑且算做建立對象的一種方式。閉包

  • 構造函數:
function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
  this.getName = function() {
    return this.name;
  };
}
var rand = new Person("Rand McKinnon", 33, "M");

上面構造函數的 getName 方法,每次實例化都會新建該函數對象,還造成了在當前狀況下並無卵用的閉包,因此構造函數添加方法用下面方式處理,工廠模式給對象添加方法的時候也應該用下面的方式避免重複構造函數對象函數

function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
  this.getName = getName
}
function getName() {
  return this.name;
};

構造函數建立對象的過程和工廠模式又是半斤八兩,至關於隱藏了建立新對象和返回該對象這兩步,構造函數內 this 指向新建對象,沒什麼不一樣。
最大不一樣點: 構造函數創造出來的對象 constructor 屬性指向該構造函數,工廠模式指向 function Object(){...}
構造函數至關於給原型鏈上加了一環,構造函數有本身的 prototype,工廠模式就是個普通函數。說到這兒我上一句話出現了漏洞,工廠模式的 constructor 指向哪得看第一句話 new 的是什麼。this

 

https://www.cnblogs.com/lihuanqing/p/7561480.htmlprototype

相關文章
相關標籤/搜索