总结自定义对象的创建方式:直接创建/工厂方式/create/构造函数/es6类语法
- 直接创建
let obj1 = { //字面量创建
name: 'obj1',
printName: function () {
console.log(this.name)
}
};
let obj1_1 = new Object(); //Object()相当于内置的构造函数
obj1_1.name = 'obj1_1'
console.log(Object.getPrototypeOf(obj1) === Object.prototype);// true
console.log(Object.getPrototypeOf(obj1_1) === Object.prototype);// true
- 工厂方式
// 原型对象是Object
function fact(name) {
let objFact = new Object();
objFact.name = name
return objFact;
}
let obj2 = fact('obj2') //用类似函数赋值的方式创建对象,提高效率,但会造成重复
console.log(Object.getPrototypeOf(obj2) === Object.prototype);// true
- Object.create
let objTemp = {
name: 'objTemp',
printName: function () {
console.log(this.name)
}
}
let obj3 = Object.create(objTemp); //存在一种继承关系,返回的应该是空实例对象
// 当同名时寻找自己,没有找到那个变量,就找原型对象
obj3.printName();//objTemp
obj3.name = 'obj3'
obj3.printName();//obj3
console.log(Object.getPrototypeOf(obj3) === objTemp);// true
- 构造函数
// 构造函数
// 修改原型,实现共享
function con(name) {
this.name = name
}
let obj4 = new con('obj4')
console.log(Object.getPrototypeOf(obj4) === con.prototype);// true
标签:总结,obj1,obj3,console,name,对象,创建,Object,let
From: https://www.cnblogs.com/chaofanhaochi/p/18315565