【问题标题】:Why in JavaScript "THIS" Returning value instead of undefined.?为什么在 JavaScript \"THIS\" 中返回值而不是未定义。?
【发布时间】: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


【解决方案1】:

据我了解,主要思想是“原型”是构造函数的常规属性。 F.prototype 属性仅在调用 new F 时使用,它分配新对象的 [[Prototype]]。

在图片中,'prototype' 是水平箭头(常规属性),[[Prototype]] 是垂直箭头(p 的继承)。

检查this thread 以及

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多