js 物件高階
阿新 • • 發佈:2021-07-14
物件的建立模式
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()
http://www.ssnd.com.cn 化妝品OEM代加工
組合
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
執行建構函式體(給物件新增屬性/方法)