javascript - 在 javascript 中向 Array.prototype 添加新方法
问题描述
我是 Javascript 语言的新手,最近我开始研究 js 原型,但对以下代码中的一些奇怪输出感到困惑:
Array.prototype.print = function() {
console.log(this)
}
[1, 2, 3, 4].print();
谁能告诉我为什么它会返回
无法读取未定义的属性“打印”
如果我声明var array = [1, 2, 3, 4]
then 调用 print 函数array.print()
,它工作正常,所以我很困惑那有什么不同?
Array.prototype.print = function() {
console.log(this)
}
var array = [1, 2, 3, 4]
array.print()
解决方案
您可以只添加一个分号来分隔对该函数的访问。
您拥有的是函数表达式的属性访问器,它带有逗号运算符,返回4
访问。ASI(自动分号插入)在这种情况下不起作用。
Array.prototype.print = function() {
console.log(this)
}[1, 2, 3, 4] //.print(); // tries to get property 4 of the function
// and then tries to call a function from undefined
它需要在函数表达式的块语句后加分号。
Array.prototype.print = function() {
console.log(this)
};
[1, 2, 3, 4].print();
推荐阅读
- reactjs - React auth 组件导致闪烁
- python - ServiceAccountCredentials.from_json_keyfile_name 要访问的 gpread 凭据在 python 中的文件位置应该是什么
- php - MySQL UPDATE 在使用 bind_param 时将值更改为“0”而不是提供的整数
- python - 如何使用 GitHub API v3 提取关于存储库的历史统计数据——观星者的数量、问题等?
- fonts - 如何从pdf中找到嵌入的字体
- flask - OSError: [Errno 98] Address already in use 如何在 python flask 中解决
- c - MPi 多播 BIGNUM
- c# - 如何对文本框 textchanged 上的过滤行求和?
- ios - Xcode 10.2 beta 10P82s 扩展没有成员
- android - 将 JSON 转换为 kotlin 数据类时出错