当我将数组和对象分别传递给function.apply()时,我得到了NaN的o/p,但当我传递对象和数组时,我得到了一个数字。为什么会发生这种情况?
既然数组也被认为是对象,为什么我不能使用它来表示来自相同上下文的数组/
我试过改变变量调用的位置,但我知道只有当它是一个参数时,顺序才是重要的。
function add() {
return arr[0] + arr[1] + this.a + this.b;
}
let obj = {
a: 1,
b: 2
};
let arr = [1, 2];
console.log(add.apply(arr, obj));
console.log(add.apply(obj, arr));
O/P
NaN
6发布于 2019-08-27 01:35:13
也许图表能帮上忙。您的函数不使用任何参数,因此您在第二个参数中为apply (应该是一个值数组)提供的内容并不重要。只有第一个参数(在函数体中变为this )才重要。
当使用arr调用时,this指向参数中提供的arr,但arr也指向同一个对象,因为它是全局的,不会在任何地方被覆盖:
function add() {
// 1 + 1 + undefined + undefined //=> NaN
return arr[0] + arr[1] + this.a + this.b;
} // | | | |
// +------+--------+---------+-----------+
// |
// V
let arr = [1, 2]; let obj = {a: 1, b: 2};
// ^
// `-----Nothing points to this
add.apply(arr) // equivalent to `add.apply(arr, obj)`, since `add` ignores parameters当您使用obj调用时,this指向参数中提供的obj,而arr再次指向全局arr对象:
function add() {
// 1 + 2 + 1 + 2 //=> 6
return arr[0] + arr[1] + this.a + this.b;
} // | | | |
// +------+--------+ +-----------+
// | |
// V V
let arr = [1, 2]; let obj = {a: 1, b: 2};
add.apply(obj) // equivalent to `add.apply(obj, arr)`, since `add` ignores parameters发布于 2019-08-27 00:57:38
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
在函数中,第一个参数变为this,第二个参数是传递给函数的参数数组
所以add.apply(arr, obj)真的应该是add.apply(arr, [obj]),this(arr)没有a和b属性
function add() {
return arr[0] + arr[1] + arr.a + arr.b;
}
// then invoking it as
add(obj);而add.apply(obj, arr)则会转化为
function add() {
return arr[0] + arr[1] + obj.a + obj.b;
}
// them invoking it as
add(1, 2);https://stackoverflow.com/questions/57661878
复制相似问题