JS 中的 new
来源:互联网 发布:倩女幽魂手游for mac 编辑:程序博客网 时间:2024/04/29 00:56
转自《深入理解JavaScript系列(26):设计模式之构造函数模式》
function Car(model, year, miles) { this.model = model; this.year = year; this.miles = miles; // 自定义一个output输出内容 this.output = function () { return this.model + "走了" + this.miles + "公里"; }}//方法1:作为函数调用Car("大叔", 2009, 20000); //添加到window对象上console.log(window.output());//方法2:在另外一个对象的作用域内调用var o = new Object();Car.call(o, "Dudu", 2010, 5000);console.log(o.output()); console.log(window.o.output()); //等同上面
该代码的方法1有点特殊,如果不适用new直接调用函数的话,this指向的是全局对象window,我们来验证一下:
//作为函数调用var tom = Car("大叔", 2009, 20000);console.log(typeof tom); // "undefined"console.log(window.output()); // "大叔走了20000公里"
这时候对象tom是undefined,而window.output()会正确输出结果,而如果使用new关键字则没有这个问题,验证如下:
//使用new 关键字var tom = new Car("大叔", 2009, 20000);console.log(typeof tom); // "object"console.log(tom.output()); // "大叔走了20000公里"
强制使用new
上述的例子展示了不使用new的问题,那么我们有没有办法让构造函数强制使用new关键字呢,答案是肯定的,上代码:
function Car(model, year, miles) { if (!(this instanceof Car)) { return new Car(model, year, miles); } this.model = model; this.year = year; this.miles = miles; this.output = function () { return this.model + "走了" + this.miles + "公里"; }}var tom = new Car("大叔", 2009, 20000);var dudu = Car("Dudu", 2010, 5000);console.log(typeof tom); // "object"console.log(tom.output()); // "大叔走了20000公里"console.log(typeof dudu); // "object"console.log(dudu.output()); // "Dudu走了5000公里"
通过判断this的instanceof是不是Car来决定返回new Car还是继续执行代码,如果使用的是new关键字,则(this instanceof Car)为真,会继续执行下面的参数赋值,如果没有用new,(this instanceof Car)就为假,就会重新new一个实例返回。
0 0
- 理解js中的new
- JS 中的 new
- 理解js中的new
- js中的new image()
- js中的的new操作
- js中的new运算符
- JS中的new操作符简单理解
- js中的New Date获取各种时间
- JS中的 new 操作符简单理解
- JS中的 new 操作符简单理解
- 理解js中的new ——2
- 理解js中的new操作符。
- js new
- js new
- js new操作符
- js的 new image()
- js new关键字
- js new Date()使用说明
- UIViewController的基本概念与生命周期
- js中instanceof的分析
- Collection、List、Set、Map、Queue关系图学习笔记2
- Python中argv的使用遇到的问题。
- 首届中国移动测试大会将于7月11日在北京举行
- JS 中的 new
- STL学习笔记之容器--multiset
- POJ-2809-2的n次方
- Java Tips
- C++ 标准输入输出 函数 fopen fread等系列函数使用总结
- static_cast, dynamic_cast, const_cast探讨
- 七牛用户上传慢诊断大全
- SAT数学解题方法介绍
- 为包含指针的关联容器指定比较类型