您的位置:首页 > 其它

如何必须用new来实例化function

2017-01-11 09:30 465 查看
我们知道使用function可以用new来实例化,那么为啥要用new?以及在代码中我们能否控制队友写代码时必须写new呢?

回顾 - 前面我们做了这样的代码结构

var God = {
//...
}; //这是母体,用来加工和扩展业务对象


var news = {}; //这是业务对象。用来传递约定好的方法和参数给母体

God.extends('news',news); //扩展方法


如何必须用new来实例化function

var GodClass = function(){
alert('god');
}


上面定义了一个函数,我们可以通过下面两种方式来调用:

//方式1
GodClass(); //'god'

//方式2
var God = new GodClass(); //'god'


两种方式都能正常执行。那么它们有什么区别呢?

var GodClass = function(){
alert(this);
}

//方式1
GodClass(); //[object Window]
//方式2
var God = new GodClass(); //[object Object]


我们发现两种调用方式,
this
不一样。

GodClass()
方式,
this
委托给了Window对象;

new GodClass()
实例化的方式,
this
指的就是实例化后的对象。

下面用代码证明

var GodClass = function(){
this.name = 'zhangsan';
}

var God = new GodClass();
console.log(God.name); //'zhangsan'
//通过实例化后的对象拿到了函数内部this的属性值


var GodClass = function(){
this.name = 'zhangsan';
}

GodClass();
console.log(Window.name); //'zhangsan'
//注意:浏览器运行,才有Winodow这个宿主对象


我们能否控制队友写代码时必须写new呢?

var GodClass = function abc(){
if(this instanceof abc){
this.name = 'zhangsan';
}else{
console.log('不要胡搞');
}
}


GodClass(); //'不要胡搞'

var God = new GodClass();
console.log(God.name); //'zhangsan'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: