JavaScript/new.target:修订间差异
来自康健生活
| 第1行: | 第1行: | ||
== 引言 == | == 引言 == | ||
== new == | == new == | ||
使用构造函数时,使用 new | 使用构造函数时,使用 new 操作符进行调用,观察 this 指向。 | ||
=== 使用 new === | |||
this 指向的是新创建的对象 | this 指向的是新创建的对象 | ||
{{leftrightflex|<syntaxhighlight lang="javascript"> | {{leftrightflex|<syntaxhighlight lang="javascript"> | ||
| 第27行: | 第28行: | ||
User {name: "Bob"} | User {name: "Bob"} | ||
</pre>}}}} | </pre>}}}} | ||
=== 不使用 new === | |||
this 遵循普通函数的 this 定义(比如在浏览器中指向 window 对象)。 | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | {{leftrightflex|<syntaxhighlight lang="javascript"> | ||
| 第52行: | 第53行: | ||
Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …} | Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …} | ||
Bob | Bob | ||
</pre>}}}} | |||
==== 修复 ==== | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
function User(name) { | |||
console.log(this); | |||
if (!(this instanceof User)) { | |||
return new User(name); | |||
} | |||
this.name = name; | |||
} | |||
var foo = User("Bob"); | |||
console.log(foo);</syntaxhighlight>|{{consoleout|<pre> | |||
Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …} | |||
User {} | |||
User {name: "Bob"} | |||
</pre>}}}} | |||
== new.target == | |||
new 调用,则函数内 new.target 指向构造函数;否则其值为 undefined。 | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
function User(name) { | |||
console.log(this); | |||
if (!new.target) { | |||
return new User(name); | |||
} | |||
this.name = name; | |||
} | |||
var foo = User("Bob"); | |||
console.log(foo);</syntaxhighlight>|{{consoleout|<pre> | |||
Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …} | |||
User {} | |||
User {name: "Bob"} | |||
</pre>}}}} | |||
== bind == | |||
普通函数 bind 操作,可以返回一个绑定的固定 this 的新函数。 | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
function User(name) { | |||
this.name = name; | |||
console.log(this); | |||
} | |||
const foo = User.bind({age: '18'}); | |||
const bar = new foo('Bob'); | |||
console.log(foo); | |||
console.log(bar);</syntaxhighlight>|{{consoleout|<pre> | |||
{age: "18", name: "Bob"} | |||
ƒ User(name) { | |||
this.name = name; | |||
console.log(this); | |||
} | |||
undefined | |||
</pre>}}}} | |||
构造函数则不同。bind 操作不能改变构造函数内的 this。 | |||
{{leftrightflex|<syntaxhighlight lang="javascript"> | |||
function User(name) { | |||
this.name = name; | |||
console.log(this); | |||
} | |||
const foo = User.bind({age: '18'}); | |||
const bar = new foo('Bob'); | |||
console.log(foo); | |||
console.log(bar);</syntaxhighlight>|{{consoleout|<pre> | |||
User {name: "Bob"} | |||
ƒ User(name) { | |||
this.name = name; | |||
console.log(this); | |||
} | |||
User {name: "Bob"} | |||
</pre>}}}} | </pre>}}}} | ||