前端笔记—从入门到坟墓[js][new 与object.create()原理][4]
前端笔记—从入门到坟墓[js][原型链解读][3]
前端笔记—从入门到坟墓[js][闭包][2]
前端笔记—从入门到坟墓[js][作用域与上下文][1]
先写一个简单用例
function Person(name){
this.name = name
}
Person.prototype.getName = function (){
console.log('name')
}
new
var person = new Person('aa')
等价于
function _new (Person,name){
var obj = new Object()
obj.__proto__ = Person.prototype
Person.call(obj,name)
//执行以下这个方法,把里边的this替换成obj执行,这样obj内就会加上新的属性了
//当有多个参数时,使用这一句:Parent.apply(obj,[].slice.call(arguments,1))
return obj
}
var person2 = _new(Person,"aa")
Object.create()
var p1 = Object.create(Person)
等价于
var p2 = function(Person){
var obj = new Object()
obj.__proto__ = Person
return obj
}()
区别
1。new作用对象必须是function,Object.create作用对象function和object都可以。
2。new产生的对象(实例对象)拥有作用对象(构造函数)的内置属性和原型上的方法,可以直接调用。
3。Object.create产生的对象(构造对象)没有作用对象的内置属性,但拥有其原型上的方法,通过.prototype调用。
产生过程总结:
new Person():
1,创建一个新的对象。
2,新的对象的隐式原型(proto)指向Person.prototype。
3,把Person的this换成新对象执行一下,目的在于把Person私有属性挂载到这个新对象上。
Object.create(Person):
1,创建一个新的对象。
2,新的对象的隐式原型(proto)指向Person。