24 lines
1.2 KiB
Plaintext
24 lines
1.2 KiB
Plaintext
---
|
|
title: '比较差异: `function Person(){}`, `var person = Person()`, 和 `var person = new Person()`?'
|
|
---
|
|
|
|
这个问题相当含糊。 我们对其意图的最好猜测是,它在询问 JavaScript 中的构造函数。 从技术上讲,`function Person(){}` 只是一个正常函数声明。 惯例是对打算作为构造函数使用的函数使用 PascalCase。
|
|
|
|
`var persons = Person()` 将`Person` 作为函数,而不是作为构造函数。 如果要将函数用作构造函数,这样的动作是常见的错误。 构造函数通常不会返回任何东西。 因此,调用构造函数像一个正常函数会返回 `undefined` ,它会被分配给指定为实例的变量。
|
|
|
|
`var persone = new Person()` 创建一个 `Person` 对象的实例,使用`new` 操作符继承了 `Person.prototype`。 另一种办法是使用 `Object.create`,例如:`Object.create(Person.prototype)`。
|
|
|
|
```js
|
|
function Person(name) {
|
|
this.name = name;
|
|
}
|
|
|
|
var person = Person('John');
|
|
console.log(person); // undefined
|
|
console.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined
|
|
|
|
var person = new Person('John');
|
|
console.log(person); // Person { name: "John" }
|
|
console.log(person.name); // "john"
|
|
```
|