如果一个构造函数,bind了一个对象,用这个构造函数创建出的实例会继承这 个对象的属性吗?为什么 ?
参考答案:
在JavaScript中,当一个构造函数通过bind
方法绑定到一个对象时,这个绑定的对象会成为该构造函数中this
的上下文。这意味着在构造函数内部,this
将引用那个绑定的对象。但是,这并不意味着新创建的实例会继承那个绑定对象的属性。
举个例子来说明:
function MyConstructor() {
this.ownProperty = 'I am from the constructor';
}
const obj = {
inheritedProperty: 'I am from the object'
};
const boundConstructor = MyConstructor.bind(obj);
const instance = new boundConstructor();
console.log(instance.ownProperty); // 'I am from the constructor'
console.log(instance.inheritedProperty); // undefined
在这个例子中,MyConstructor
是一个构造函数,obj
是一个对象。我们通过bind
方法将MyConstructor
的this
上下文绑定到obj
上,然后创建了instance
这个新实例。尽管instance
是在obj
的上下文中创建的,但instance
只继承了MyConstructor
中的属性,而没有继承obj
中的属性。
这是因为new
操作符在创建新实例时会执行以下步骤:
- 创建一个新的空对象。
- 将这个新对象的内部原型链接到构造函数的
prototype
对象。 - 将构造函数的作用域赋给新对象(即设置
this
为新对象)。 - 如果该函数没有返回其他对象,则返回新对象。
由于bind
方法只改变了this
的上下文,并没有改变构造函数的原型链或继承关系,因此新创建的实例不会继承绑定对象的属性。