一、字面量创建对象
- 特点
1)代码大量重复
2)内存空间浪费:每个对象都指向堆的一个内存
<script>
// 通过字面量创建对象
// 1)代码大量重复
// 2)内存空间浪费
let wc = {`在这里插入代码片`
name: 'wangcai',
age: 11,
height: 188,
address: 'beijing',
coding: function() {
console.log('coding.......');
}
}
let xq = {
name: 'xiaoqiang',
age: 11,
height: 168,
address: 'beijing',
coding: function() {
console.log('coding.......');
}
}
let jj = { //
name: 'xiaoqiang',
age: 25,
height: 158,
address: 'beijing',
coding: function() {
console.log('coding.......');
}
}
</script>
二、工厂函数
<script>
// 工厂函数
function createPerson(name, age, height, address) {
let p = {}
p.name = name;
p.age = age;
p.height = height;
p.adress = address;
p.coding = function() {
console.log('coding....');
}
return p;
}
let wc = createPerson('wangcai', 11, 180, 'bj');
wc.coding(); //coding....
let xq = createPerson('xq', 12, 160, 'zz');
wc.coding(); //coding....
let jj = createPerson('jj', 16, 170, 'bj');
wc.coding(); //coding....
// wc xq jj 都是字面量对象
// 需求:不同对象有不同类
console.log(wc instanceof Object); //true
console.log(xq instanceof Object); //true
console.log(jj instanceof Object); //true
</script>
三、构造函数创建对象
new一个对象,new干了些什么:
- 在构造器里面创建一个新对象
- 这个对象内部的__protot__属性会被赋值为该构造函数的prototype属性
- 让构造器里面的this指向这个对象
- 执行构造器中的代码
- 如果构造器没有返回对象,则返回生面的创建出来的对象
JS函数有多重角色 构造器就是其中之一
<script>
function Fn() {
console.log('fn.......');
// 1)内部创建一个新对象
// 2)让函数中的this绑定到新对象上 new绑定
// 3)执行类(函数) 中的代码
// 4)返回上面的新对象
}
// new 一个构造器(类)
let f = new Fn();
console.log(f);
console.log(f instanceof Fn); //true
</script>
使用构造器形式创建对象缺陷:
也会造成内存空间浪费
<script>
// 使用构造器形式创建对象
// 缺陷:也会造成内存空间浪费
function Person(name, age, height, address) {
this.name = name;
this.age = age;
this.height = height;
this.address = address;
this.coding = function() {
console.log(this.name);
}
}
let wc = new Person('wangcai', 11, 180, 'bj');
wc.coding();
let xq = new Person('xq', 12, 160, 'zz');
xq.coding();
let jj = new Person('jj', 16, 170, 'bj');
jj.coding();
// 问:有没有更加优雅的方式创建对象?
// 答:有 构造器 + 原型对象形式
</script>