05------JS面向對象高級

對象創建模式

1.Object構造函數模式

  • 方法:先創建空Object對象,再動態添加屬性/方法
  • 適用場景:起始時不確定對象內部數據
  • 問題:語句太多
// 一個學生
var s = new Object()
s = {} //內部數據不確定
//動態添加屬性和方法
s.name = 'alice'
s.score= 90
s.setScore = function (score) {
	this.score= score
}
console.log(s.name. s.score)
s.setScore (95)
console.log(s.name, s.score)

2.對象字面量模式

  • 方法:使用{}創建對象,同時指定屬性/方法
  • 適用場景:起始時對象內部數據是確定的
  • 問題:如果創建多個對象,有重複代碼
var s = {
	name: 'alice',
	score: 90,
	setScore : function (score) {
		this.score= score
	}	
}
console.log(s.name. s.score)
s.setScore (98)
console.log(s.name, s.score)

3.工廠模式

  • 方法:通過工廠函數動態創建對象並返回
  • 適用場景:需要創建多個對象
  • 問題:對象沒有一個具體的類型,都是Object對象
function createStudent(name, score) {
	var stu = {
		name: name,
		score: score,	
		setSorce: function (score) {
			this.score= score
		}
	}
	return stu
}

var stu1 = createStudent('Tom', 78)
var stu2 = createStudent('alice', 95)

4.自定義構造函數模式

  • 方法:自定義構造函數,通過new創建對象
  • 適用場景:需要創建多個類型確定的對象
  • 問題:每個對象都有相同的數據,浪費內存
//定義類型
function Student (name, score) {
	this.name = name
	this.score= score
	this.setScore = function (score) {
		this.score= score
	}	
}
var stu1 = new Student('Tom', 78)
var stu2 = new Student('Bob', 65)
console.log(stu1  instanceof Student) // true

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

  • 方法:自定義構造函數,屬性在函數中初始化,方法添加到原型上
  • 適用場景:需要創建多個類型確定的對象
function Student (name, score) {
	this.name = name
	this.score= score
}
Student.prototype.setScore = function (score) {
	this.score= score
}	
var stu1 = new Student('Tom', 78)
var stu2 = new Student('Bob', 65)
console.log(stu1)
console.log(stu2)

繼承模式

1.原型鏈繼承

  • 關鍵:子類型的原型爲父類型的一個實例對象
// 父類型
function Parent() {
	this.parentProp = 'parent'
}
Parent.prototype.showParentProp = function () {
	console.log(this.parentProp)
}
// 子類型
function Child() {
	this.childProp = 'child'
}
// 子類型的原型爲父類型的一個實例對象
Child.prototype = new Parent()
Child.prototype.showChildProp = function () {
	console.log(this.childProp)
}

var child = new Child()
child.showParentProp() // parent
child.showChildProp() // child

2.借用構造函數繼承

  • 方法:
    • 定義父類型構造函數
    • 定義子類型構造函數
    • 在子類型構造函數中調用父類型構造函數
  • 關鍵:在子類型構造函數中通過call()調用父類型構造函數
function Person(name, age) {
	this.name = name
	this.age = age
}
function Student(name, age, score) {
	Person.call(this, name, age) // 相當於:this.Person(name, age)
	this.score = score
}

var stu1 = new Student('Tom', 25, 89)
console.log(stu1)

3.原型鏈+借用構造函數的組合繼承

function Person(name, age) {
	this.name = name
	this.age = age
}
Person.prototype.setName = function (name) {
	this.name = name
}
function Student(name, age, score) {
	Person.call(this, name, age) // 相當於:this.Person(name, age)
	this.score = score
}
Student.prototype.setScore = function (score) {
	this.score = score
}
var stu1 = new Student('Tom', 25, 89)
stu1.setName('alice')
stu1.setScore(95)
console.log(stu1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章