var o = { 'name':'lee' }
var a = ['reg','blue']
var getDataType = function(o){
if(typeof o == 'object'){
if( typeof o.length == 'number' ){
return 'Array'
}else{
return 'Object'
}
}else{
return 'param is no object type'
}
}
alert( getDataType(o) ) // Object
alert( getDataType(a) ) // Array
alert( getDataType(1) ) // param is no object type
alert( getDataType(true) )// param is no object type
alert( getDataType('a') ) // param is no object type
现在写一个函数,这个函数的返回值是一个对象,来观察一下这个对象,和函数体内this指向
①,对象a就是一个空对象
②,对象a没有color属性
③,对象a原型指向Object.prototype
④,函数体内this指向window(上图可见,没调用函数之前,window.color属性不存在)
在执行函数时,加一个new试试看有啥效果:
①,没有return,这个函数居然返回了一个对象
②,对象a有个color属性
③,对象a的原型指向了这个构造函数的prototype属性
④,window对象没有color属性
⑤,this指向了对象a
由上得出总结new的作用:
①,new能让一个构造函数返回一个对象(下面称为A)而无需return
②,new会让函数体内的this指向这个A
③,new会让A的原型指向这个构造函数的prototype属性
PS:
①,new只用了三个字符,却实现了很多功能,非常贴心,可以称呼new为语法糖或贴心语法( syntactic sugar )
②,一个函数自带prototype对象,而且里面默认有一个constructor属性,这个属性返回实例对象的构造函数,如果你重新给prototype对象赋值,小心不要覆盖掉它
③,如果使用new,函数内就别 return一个对象 了 ,这样返回的是return后面的对象,this不会指向它
④,就算函数体内空空如也,new的作用不变