如何强制使用"new"来调用构造函数
3.强制使用new调用构造函数
======================
**知识点**
1. this的指向
2. 命名规范
3. 中间对象that
-------------------------------------------------------
1.this的指向
------------
- new: 指向新对象
- 不用new: 指向window
-------------------------------------------------------
2.命名规范
--------
编程约定: 凡首字母大写的函数一律视为构造函数,必须new调用
-------------------------------------------------------
3.中间对象that
-------------
利用构造函数可返回任意对象特性,使构造函数具备一定的容错性
-------------------------------------------------------
### 示例代码: code/demo03.html
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>强制使用new来调用构造函数</title>
</head>
<body>
<script>
var Mobile = function (brand, price) {
this.brand = brand;
this.price = price;
this.getInfo = function () {
return this.brand + '价格是: ' + this.price;
}
};
var mobile1 = new Mobile('iPhone XR', 6899);
console.log(mobile1.getInfo());
// 不用 new 来调用 构造函数
var mobile2 = Mobile('华为 P20 Meta20', 5899);
console.log(mobile2); // 发现未定义
// console.log(mobile2.getInfo()); // getInfo()找不到
// 原因是 : this 指向了全局对象 window 并非新对象
console.log(window.getInfo());
console.log(this.getInfo());
// 可见,如果是一个用来生成新对象的构造函数,在调用时忘记了使用new 是非常危险的
// 有二种方案
// 1. 使用命名规范,凡首字母大写的函数,一律视为构造函数,必须使用new调用,但是防君子不防小人
// 2. 借用中间对象that来实现,确保总会返回一个正确的对象(其实这个在上个案例中我们遇到过,现活学活用)
// 下面对 Mobile函数进行改写
var Mobile = function (brand, price) {
var that = {};
that.brand = brand;
that.price = price;
that.getInfo = function () {
return that.brand + '价格是: ' + that.price;
// 其实这里也可以使用this,想想这是为什么? 因为这个this,就是指当前对象: that
// return this.brand + '价格是: ' + this.price;
};
return that; // 显示的返回 that 对象
};
var mobile1 = new Mobile('小米8', 3599);
console.log(mobile1.getInfo());
// 如果用户忘记了使用: new, 使用可以输出正确结果
var mobile2 = Mobile('小米8', 3599);
console.log(mobile2.getInfo());
</script>
</body>
</html>
```