JavaScript设计模式_创建对象的安全模式

window.onload=function(){
			var Book=function(title,time,type){
				this.title=title;
				this.time=time;
				this.type=type;
			}
			var book=Book("JavaScript","2014","js");
			console.log(book);//undefined
            console.log(window.title);//JavaScript
            console.log(window.time);//2014
            console.log(window.type);//js
		}

未使用new关键词进行实例化,new关键字的作用是对当前this对象的不断赋值(即更新当前this的指向),然而上述代码没有使用new关键字,所以此时的this指向的当前对象是window,所以这些属性就被添加到window上,而book变量最终作用是得到Book这个函数的执行结果(return的返回值),由于函数中未定义返回值,所以book变量执行结果为undefined。

安全模式创建对象:

      var Book2=function(title,time,type){
      	if(this instanceof Book2){//加入原型判断,判断this是否属于Book2类型,如果是则说明是new创建的Book2的一个实例对象
      		this.title=title;
					this.time=time;
					this.type=type;
      	}else{
      		return new Book2(title,time,type);//非new创建的实例对象,重新创建一个实例对象
      	}				
			}
			var book2=Book2("HTML","2016","web");
			console.log(book2);//undefined
      console.log(window.title);//JavaScript
      console.log(window.time);//2014
      console.log(window.type);//js

猜你喜欢

转载自blog.csdn.net/CWH0908/article/details/88935132