【发布时间】:2022-11-02 03:17:49
【问题描述】:
由于隐式绑定,我们知道何时使用点运算符调用任何对象的方法,就像
// Example: one
const obj = {
name: 'Toseef',
getName() {
return this.name
}
}
obj.getName()
“THIS”运算符针对点左侧的调用对象,很好理解,而且我们也知道当我们调用内部嵌套方法而不调用或绑定时,“THIS”只针对点最左侧的对象,相似
// Example: two
const obj = {
name: 'Toseef',
nested: {
getName() {
return this.name
}
}
}
obj.nested.getName() // will return undefined, because nested don't have name.
在这种情况下,“THIS”将返回 undefined,RIGHT。! 但是我的问题是当我们调用对象的一个方法并且该方法不能直接在对象中使用时,所以它会去原型对象找到我们需要的方法。!让我们看看示例
// Example: Three
Person.prototype.getName = function() {
return this.name;
}
function Person(name, age) {
this.name = name;
this.age =age;
}
const p = new Person("toseef", 21);
p.getName() // will return "toseef" but why
如我们所见,我们在 p 对象中调用 getName 方法,该对象具有称为原型的嵌套对象。因为每个构造函数都有方法原型。
意味着它看起来像 p.prototype.getName(),但我们知道没有调用或绑定“THIS”只针对最左侧的对象,所以为什么 p.prototype.getName() 返回值而不是未定义,因为嵌套对象不有名字。!!!
// Example: Three
Person.prototype.getName = function() {
return this.name;
}
function Person(name, age) {
this.name = name;
this. Age =age;
}
const p = new Person("toseef", 21);
p.getName() // will return "toseef" but why
根据我的说法,p.prototype.getName() 应该返回未定义,因为“THIS”是针对原型对象而不是 p 并且原型没有名称。请让我理解为什么“THIS”针对的是 p 而不是原型。!!!
【问题讨论】:
-
doc 声明“当函数用作构造函数时(使用
new关键字),它的this绑定到正在构造的新对象。”
标签: javascript javascript-objects prototype prototypal-inheritance prototype-chain