我是新手
JS
尝试绑定构造函数对象:
"use strict";
let Person = function(name){
this.name = name;
}
let age = {
age: 128
}
let AgedPerson = Person.bind(age)
console.log(new AgedPerson("John"))
由于
bind
本质上设置了一个上下文,其中 this
指向某个对象,然后 new
初始化 this
并返回它,我预计将打印以下内容:
{
age: 128,
name: "John"
}
但是却得到了
{
name: "John"
}
您能否解释一下为什么创建对象后
age
字段丢失了?
new
关键字 时,将使用设置为新空对象的 this
值来调用该函数,无论您事先是否在该函数上使用 .bind()
(即: this
您设置的值将被忽略)。
由于您的函数不返回任何内容并且您使用
new
关键字,因此函数的默认行为是在执行完成后返回 this
值。在您的情况下,调用 AgedPerson
,并将 this
设置为空对象 {}
。然后在函数内更新 this
以向其添加 name
属性,然后隐式返回该属性。
一般情况下,当您被调用时,.bind()
就会发挥作用(例如:使用 ()
,以及 .call()
或 .apply()
),但在使用 new
时则不会,例如:
"use strict";
const Person = function(name) {
this.name = name;
}
const age = { age: 128 };
const AgedPerson = Person.bind(age)
AgedPerson("Foo"); // modifies the age object by reference
console.log(age); // { age: 128, name: "Foo" }