一、创建对象的方式
1、new object()
var obj = new Object()
console.log(obj) //{}
1.1、new内部过程发生了什么?
- 创建一个新对象
- 新对象的_proto_属性指向构造函数的原型对象
- 将新对象绑定到该函数的this上
- 返回这个对象
1.2、手写实现new
// new 生成对象的过程
// 1、生成新对象
// 2、链接到原型
// 3、绑定 this
// 4、返回新对象
// 参数:
// 1、cons: 接收一个构造函数
// 2、args:传入构造函数的参数
function createobj(cons,...args){
let obj={}
obj.__proto__=cons.prototype
let result=cons.apply(obj,args)
return result instanceof Object?result:obj
}
//构造函数
function Test(name, age) {
this.name = name
this.age = age
}
Test.prototype.getName=function(){
console.log('11111'+this.name)
}
let a=new createobj(Test,'yyqx',18)
console.log(a.name) //yyqx
1.3、检测对象中是否存在某个属性
- in : 检测对象属性(私有 + 共有):会遍历对象的原型上是否存在某个属性
- hasOwnProperty(私有):检测当前属性是否为对象的私有属性.
var obj = {
a:1
}
obj.__proto__.b=2
console.log('a' in obj) // true
console.log('b' in obj) // true
obj.hasOwnProperty('a')//true
obj.hasOwnProperty('b') //false
2、字面量
{}是javascript对象字面量创建的形式,其本质和new Object()并无区别,默认都是继承了Object对象上的prototype。
let obj={
name:'xh'
}
3、Object.create(null)
Object.create(proto,[propertiesObject]) proto :新创建对象的原型对象。
propertiesObject:可选。需要传入一个对象,可为创建的新对象设置属性和值;
使用Object.create()是将对象继承到原型链上,然后可以通过对象实例的__proto__属性进行访问原型链上的属性。
var test = Object.create({x:123,y:345});
console.log(test);//{}
console.log(test.x);//123
console.log(test.__proto__.x);//123
console.log(test.__proto__.x === test.x);//true
var test1 = new Object({x:123,y:345});
console.log(test1);//{x:123,y:345}
console.log(test1.x);//123
console.log(test1.__proto__.x);//undefined
console.log(test1.__proto__.x === test1.x);//false
var test2 = {x:123,y:345};
console.log(test2);//{x:123,y:345};
console.log(test2.x);//123
console.log(test2.__proto__.x);//undefined
console.log(test2.__proto__.x === test2.x);//false
三者的区别
-
new和字面量创建的对象的原型指向Object.prototype,会继承Object的属性和方法。
-
Object.create(null)创建的对象是一个空对象,其原型指向null,在该对象上没有继承 Object.prototype 原型链上的属性或者方法,例如:toString(), hasOwnProperty()等方法。