03对象高级
对象的创建模式
1 Object构造函数模式
var obj = {};
obj.name = 'Tom'
obj.setName = function(name){this.name=name}
* 套路: 先创建空Object对象, 再动态添加属性/方法
* 适用场景: 创建一个对象,起始时不确定对象内部数据
* 问题: 语句太多
2 对象字面量模式
var obj = {
name : 'Tom',
setName : function(name){this.name = name}
}
* 套路: 使用{}创建对象, 同时指定属性/方法
* 适用场景: 创建一个对象,起始时对象内部数据是确定的
* 问题: 如果创建多个对象, 有重复代码
3 构造函数模式 【真正使用】
function Person(name, age) {
this.name = name;
this.age = age;
this.setName = function(name){this.name=name;};
}
new Person('tom', 12);
* 套路: 自定义构造函数, 通过new创建对象
* 适用场景: 需要创建多个类型确定的对象
* 问题: 每个对象都有相同的数据(方法), 浪费内存
4 工厂模式 【不常用】
//返回一个对象的函数===>工厂函数
function createPerson(name, age) {
var obj = {
name: name,
age: age,
setName: function (name) {
this.name = name}
}
return obj
}
* 套路: 通过工厂函数动态创建对象并返回
* 适用场景: 需要创建多个对象
* 问题: 对象没有一个具体的类型, 都是Object类型
5 构造函数+原型的组合模式
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.setName = function(name){this.name=name;};
new Person('tom', 12);
* 套路: 自定义构造函数, 属性在函数中初始化, 方法添加到原型上
* 适用场景: 需要创建多个类型确定的对象
优点:节省内存,程序员的追求
- 还有其他方法,
继承模式
1: 原型链继承 【重点】
function Parent(){}
Parent.prototype.test = function(){};
function Child(){}
Child.prototype = new Parent(); // 子类型的原型指向父类型实例
// 最好加下面的指向
Child.prototype.constructor = Child
var child = new Child(); //有test()
1.套路
-
定义父类型构造函数
-
给父类型的原型添加方法
-
定义子类型的构造函数
-
创建父类型的对象赋值给子类型的原型
-
将子类型原型的构造属性设置为子类型
-
给子类型原型添加方法
-
创建子类型的对象: 可以调用父类型的方法
2.关键
- 子类型的原型为父类型的一个实例对象
方式2: 借用构造函数继承(假的)
1.套路:
-
定义父类型构造函数
-
定义子类型构造函数
-
在子类型构造函数中调用父类型构造
2.关键:
- 在子类型构造函数中通用call()调用父类型构造函数
function Parent(xxx){this.xxx = xxx}
Parent.prototype.test = function(){};
function Child(xxx,yyy){
Parent.call(this, xxx);
//借用构造函数 this.Parent(xxx)
// 父类call子类的实例对象
}
var child = new Child('a', 'b'); //child.xxx为'a', 但child没有test()
function Person(name, age) {
this.name = name
this.age = age
}
function Student(name, age, price) {
Person.call(this, name, age) //相当于this.Person(name, age)
/* this.name = name
this.age = age*/
this.price = price
}
var s = new Student('Tom', 20, 14000)
console.log(s.name, s.age, s.price)
方式3: 原型链+构造函数的组合继承 【实际使用】
-
利用原型链实现对父类型对象的方法继承
-
利用super()借用父类型构建函数初始化相同属性
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
function Student(name, age, price) {
Person.call(this, name, age) // 为了得到属性
this.price = price
}
Student.prototype = new Person() // 为了能看到父类型的方法
Student.prototype.constructor = Student //修正constructor属性
Student.prototype.setPrice = function (price) {
this.price = price
}
var s = new Student('Tom', 24, 15000)
s.setName('Bob')
s.setPrice(16000)
console.log(s.name, s.age, s.price)
此处才看见call()函数的作用,调用父函数
组合
- new一个对象背后做了些什么?
- 创建一个空对象
- 给对象设置__proto__, 值为构造函数对象的prototype属性值 this.proto = Fn.prototype
- 执行构造函数体(给对象添加属性/方法)
整理不易,关注和收藏后拿走!
欢迎专注我的公众号:AdaCoding