在思考原型对象中的this时发现,使用字面量直接调用会报错,但是使用变量调用就不会
如:
Array.prototype.hello=function(){
console.log('hello',this);
}
let p=[1,3];
p.hello();//输出hello,[1,3]
[1,3].hello();//报错
想到可能是没加括号的问题,给字面量加上括号后:
Array.prototype.hello=function(){
console.log('hello',this);
}
([1,3]).hello();//输出全局global变量和报错
并且其中的this==global
上面的执行环境是node
今天试着在html文件中用<script>标签引入


加了括号后this指向window,为什么加了括号之后的this会指向全局变量,而且为什么在控制台可以正常执行,在别的环境下会报错?
回答:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script>
Array.prototype.hello=function(){
console.log('hello',this);
};
[1,3].hello()
</script>
</body>
</html>
不看我的解释,你能发现你我代码的不同之处吗?
分号在 javascript 中是可选的,但是某些情况,你最好加上,不加的话你写的代码相当于:
Array.prototype.hello= function() { ... }[1,3].hello();//它会被认为一条语句
至于你在node下会出错,我合理怀疑你 [1,3].hello()前一条语句最后也少了分号,(虽然你贴出来的代码里是有的,我试了一下并不会报错)