JavaScript中对象的创建方式有以下几种:
- object 构造函数
let a = new Object()
a.name = 'king'
a.getName = function () {
console.log(this.name)
}
缺点:动态添加属性,代码量大
- 对象字面量
let b = {
name: 'king', getName: function () {
console.log(this.name)
}
}
缺点:创建多个对象时,有重复代码,不能复用
- 工厂模式
function C(name) {
let obj = {
name: name,
getName: function () {
console.log(this.name)
}
}
return obj
}
let c = C('king')
缺点:对象没有特定的类型,都是Object,不好区分
- 构造函数
function D(name) {
this.name = name
this.getName = function () {
console.log(this.name)
}
}
let d = new D('king')
缺点:每次创建对象都产生新的方法,不能复用,浪费内存
- 构造函数+原型
function E(name) {
this.name = name
}
E.prototype.getName = function () {
console.log(this.name)
}
let e = new E('king')
属性在构造函数中,方法绑定在原型上,节省内存
继承
- 借用构造函数继承
这里用到了call
方法来改变this指向来实现继承属性
function Person(name){
this.name = name
}
Person.prototype.getName = function(){
console.log(this.name)
}
function Boy(name){
//借用构造函数改变this指向,继承父类的属性
Person.call(this,name)
this.gender = 'male'
}
- 原型链继承
//将子类型的原型对象指向父类型的实例来继承父类型的方法
Boy.prototype = new Person()
//上一步操作会使得子类型原型中的constructor指向父类,需要更改为子类函数
Boy.prototype.constructor=Boy
- 构造函数+原型链组合继承
用构造函数继承属性,原型链继承方法,以上两块代码结合即为组合继承。
网友评论