为什么我必须调用 () push() JS 函数并重新设置它以获得预期的结果?
Why do I have to call() the push() JS function and re-set this to get the expected results?
我一直在阅读 ki.js source code and stumbled over a strange use of the call() function(参见 GitHub 上的 function i(a)
)。首先,我出于我的目的简化了 i(a)
函数,现在该函数如下所示:
function ki(selector, arr) {
document.querySelectorAll(selector).forEach((el) => { arr.push.call(this, el); });
}
当我这样调用我的函数时:new ki(".test", []);
,我得到了预期的结果——一个包含 DOM 对象的对象和一个从 ki() 函数复制的原型 属性原型.
但是,当我稍微将 ki() 函数更改为此:(删除,在我看来不必要的 call() 函数):
function ki(selector, arr) {
document.querySelectorAll(selector).forEach((el) => { arr.push(el); });
}
执行new ki(".test", []);
将导致一个对象没有任何DOM对象,只有构造函数继承的原型属性。
这是我不明白的。为什么有必要操纵 array.prototype.push() 源代码(在不同的上下文中将 this
替换为 this
)?此外,这段代码在严格模式下是否也能正常工作?
感谢您的帮助。
如果 ki 函数用作构造函数,则 el 对象不会被推送到 arr 数组,而是推送到 this 值,这将是创建的对象
arr = new Array
arr2 = new Array
document.querySelectorAll('a').forEach((el) => { arr2.push.call(arr, el); })
希望对您有所帮助
先arr.push(el)
也可以写成arr.push.call(arr, el)
。眼熟?
但是 this
!== arr
在你的代码中。
在该代码中 arr.push.call(...)
用作 Array.prototype.push.call(...)
的 shorthand。另一种常见的写法是 [].push.call(...)
.
旁注:等到你开始编写 Function.prototype.apply.call(...)
我一直在阅读 ki.js source code and stumbled over a strange use of the call() function(参见 GitHub 上的 function i(a)
)。首先,我出于我的目的简化了 i(a)
函数,现在该函数如下所示:
function ki(selector, arr) {
document.querySelectorAll(selector).forEach((el) => { arr.push.call(this, el); });
}
当我这样调用我的函数时:new ki(".test", []);
,我得到了预期的结果——一个包含 DOM 对象的对象和一个从 ki() 函数复制的原型 属性原型.
但是,当我稍微将 ki() 函数更改为此:(删除,在我看来不必要的 call() 函数):
function ki(selector, arr) {
document.querySelectorAll(selector).forEach((el) => { arr.push(el); });
}
执行new ki(".test", []);
将导致一个对象没有任何DOM对象,只有构造函数继承的原型属性。
这是我不明白的。为什么有必要操纵 array.prototype.push() 源代码(在不同的上下文中将 this
替换为 this
)?此外,这段代码在严格模式下是否也能正常工作?
感谢您的帮助。
如果 ki 函数用作构造函数,则 el 对象不会被推送到 arr 数组,而是推送到 this 值,这将是创建的对象
arr = new Array
arr2 = new Array
document.querySelectorAll('a').forEach((el) => { arr2.push.call(arr, el); })
希望对您有所帮助
先arr.push(el)
也可以写成arr.push.call(arr, el)
。眼熟?
但是 this
!== arr
在你的代码中。
在该代码中 arr.push.call(...)
用作 Array.prototype.push.call(...)
的 shorthand。另一种常见的写法是 [].push.call(...)
.
旁注:等到你开始编写 Function.prototype.apply.call(...)