沐鳴登錄網站_js 對象高級

對象的創建模式

Object構造函數模式

var obj = {};
obj.name = ‘Tom‘
obj.setName = function(name){this.name=name}

對象字面量模式

var obj = {
  name : ‘Tom‘,
  setName : function(name){this.name = name}
}

構造函數模式

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.setName = function(name){this.name=name;};
}
new Person(‘tom‘, 12);

構造函數+原型的組合模式

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.setName = function(name){this.name=name;};
new Person(‘tom‘, 12);

繼承模式

原型鏈繼承 : 得到方法

function Parent(){}
Parent.prototype.test = function(){};
function Child(){}
Child.prototype = new Parent(); // 子類型的原型指向父類型實例
Child.prototype.constructor = Child
var child = new Child(); //有test()

借用構造函數 : 得到屬性

function Parent(xxx){this.xxx = xxx}
Parent.prototype.test = function(){};
function Child(xxx,yyy){
    Parent.call(this, xxx);//借用構造函數   this.Parent(xxx)
}
var child = new Child(‘a‘, ‘b‘);  //child.xxx為‘a‘, 但child沒有test()

組合

function Parent(xxx){this.xxx = xxx}
Parent.prototype.test = function(){};
function Child(xxx,yyy){
    Parent.call(this, xxx);//借用構造函數   this.Parent(xxx)
}
Child.prototype = new Parent(); //得到test()
var child = new Child(); //child.xxx為‘a‘, 也有test()

new一個對象背後做了些什麼?

創建一個空對象

給對象設置__proto__, 值為構造函數對象的prototype屬性值 this.proto = Fn.prototype

執行構造函數體(給對象添加屬性/方法)

站長推薦

1.雲服務推薦: 國內主流雲服務商,各類雲產品的最新活動,優惠券領取。地址:阿里雲騰訊雲華為雲

鏈接: http://www.fly63.com/article/detial/10163