gpt4 book ai didi

javascript - 从 Javascript 方法访问调用对象

转载 作者:行者123 更新时间:2023-11-30 06:51:39 26 4
gpt4 key购买 nike

在 JavaScript 中,对于定义在对象内部的匿名函数,this 关键字指的是对象本身。但是,当函数定义在对象范围之外时,this 指的是 window 对象,示例:

function foo() {
console.log(this)
}

let A = {
att: foo(),
att2: "bla"
}

A.foo();

[编辑]:我在原始代码中犯了一个错误,我的意思是将函数调用为 A.att()(我有义务保留 att: foo()。我的代码基本上如下:

function foo() {
console.log(this)
}

let A = {
att: foo(),
att2: "bla"
}

A.att();

这里输出的是对象Window,而不是我要访问的对象A。而且我不能改变A,那么如何从foo()访问A呢?

最佳答案

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode. In most cases, the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called.

要自己操作this 对象,您可以使用JS 方法callapplybind

让我们用例子来演示每一个:

Function.prototype.call()

详细信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

function foo() {
console.log(this)
}

var A = {
att: foo,
att2: "bla"
}

foo.call(A);

Function.prototype.apply()

详细信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

function foo() {
console.log(this)
}

var A = {
att: foo,
att2: "bla"
}

foo.apply(A);

Function.prototype.bind()

详细信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

function foo() {
console.log(this)
}

var A = {
att: foo,
att2: "bla"
}

var x = foo.bind(A);
x();

关于javascript - 从 Javascript 方法访问调用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41973707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com