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)
发布了56 篇原创文章 · 获赞 32 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/hry1243916844/article/details/104059578