对象的创建
1、字面量
var obj = {
name: '我是一个对象'
}
2、构造函数
function Obj() {
this.name = '我是一个对象';
this.color = 'red'
}
var obj = new Obj()
3、Object.creat()
var o = {
name: '我是一个对象'
}
var obj = Object.create(o)
new与Object.create()的区别
new构造函数实例化一个对象:创建一个Object对象并将其__proto__赋值为构造函数的prototype,将this绑定到构造函数;object.create(obj)创建一个对象:创建一个空的函数对象,将函数对象原型对象指向obj 返回函数对象实例
//new的实现方式
var obj = new Object();
obj.__proto__=Obj.prototype; // Obj-构造函数
Obj.call(obj); // 绑定this到构造函数
//Object.create()实现方式
Object.creat=function(o){
var F = function() {};
F.prototype=o;
return new F();
}
_proto_ 与prototype的区别
_proto_ 隐式原型(对象才有、构成原型链、沿其查找值); prototype 显示原型(函数才有、实现继承)。
实例对象的__proto__指向的原型对象与他的构造函数的prototype指向同一原型对象
因此Object.create()创建的对象无法获取构造函数上的属性、并且无法获取到Obj原型上的属性,因为new F的__proto__指向Obj,所以
Obj.prototype.color = '颜色'
var obj1 = Object.creat(Obj)
obj1.color // undefined
new 时 obj2.__proto__指向Obj.prototype,所以
Obj.prototype.color = '颜色'
var obj2 = new Obj()
obj2.color // 颜色
instanceof原理
判断实例的构造函数
判断构造函数的prototype是否在实例的原型链上
类的继承
1、构造函数实现继承
部分继承(只继承构造函数里的内容)
var Parent=function(){
this.parentname='父'
}
var child=function(){
Parent.call(this) // 转移this
this.childname='子'
}
2、原型链实现继承
改变一个实例属性(引用类型)另一个跟着变
var Parent = function() {}
Parent.prototype.parentname='父'
var Child = function(){}
Child.prototype=new Parent()
Child.prototype.constructor=Child
var a1=new child();var a2=new child()
3、组合方式
parent被多次实例化
var Parent=function(name){
this.title=name
}
Parent.prototype.getName=function(){
return this.title
}
var Child=function(name){
Parent.call(this,name)
this.age='18'
}
Child.prototype=new Parent()
Child.prototype.constructor=Child
4、组合优化
var Parent=function(name){
this.title=name
}
Parent.prototype.getName=function(){
return this.title
}
var Child=function(name){
Parent.call(this,name)
this.age='18'
}
var immediate= function(){}
immediate.prototype=Parent.prototype
Child.prototype=new immediate()
Child.prototype.constructor=Child