【JavaScript】对象创建模式与继承模式

对象创建模式

1、通过 Object() 构造函数模式

var obj = new Object()
obj.name = "张三"
obj.age = 12
obj.setName = function(name){
 this.name = name
}

2、通过对象字面量创建

var obj = {
 name:"张三",
 age:12,
 setName:function(name){
  this.name = name
 }
}

3、通过工厂模式(无法显示对象具体类型)

function createPerson(name,age){
 var obj={
  name = name,
  age = age,
  setName:function(name){
   this.name = name
  }
 }
 return obj
}
var p = createPerson('张三',12)

4、通过自定义构造函数(可以显示具体的对象类型)

function Person(name,age){
 this.name = name
 this.age = age
 this.setName = function(name){
  this.name = name
 }
}
var p = new Person('张三',12)
console.log(p.name)
console.log(p.setName("李四"))

5、构造函数+原型的组合模式

只在构造函数中初始化属性,方法通过原型对象构建

function Person(name,age){
 this.name = name
 this.age = age
}
Person.prototype.setName = function(name){
 this.name = name
}
var p = new Person('张三',12)
console.log(p.name)
console.log(p.setName("李四"))

继承模式

1、原型链继承

//父类型
function A(){
 this.name = 'A'
}
A.prototype.setAName = function(){
 console.log(this.name)
}
//子类型
function B(){
 this.name = 'B'
}
//创建一个父类型的实例对象,作为子类型的原型对象,实现继承
B.prototype = new A()
//由于改变了原型对象为 A 的实例对象,它的构造函数指向的是 A()
//所以还要将构造函数重新改为 B
B.prototype.constructor = B
B.prototype.setBName = function(){
 console.log(this.name)
}
var b = new B()
b.setAName()//不会报错,可以调用到父类型的方法

2、借用构造函数继承

//父类型
function A(name){
 this.name = name
}
//子类型
function B(name,age){
 //借用了父构造函数,简化代码
 A.call(this,name)
 this.age = age
}
var p = new B("张三",12)

3、组合继承

//父类型
function A(name,age){
 this.name = name
 this.age = age
}
A.prototype.setAName = function(){
 console.log(this.name)
}
//子类型
function B(name,age,address){
 A.call(this,name,age)//是为了获得父类型的属性
 this.address = address
}
//获得父类型的方法
B.prototype = new A()
//修正 constructor 指向
B.prototype.constructor = B
B.prototype.setBName = function(){
 console.log(this.name)
}
var b = new B("张三",12,“阿巴阿巴”)
b.setAName()//不会报错,可以调用到父类型的方法
posted @ 2022-01-27 17:31  RikkaXl  阅读(32)  评论(0)    收藏  举报