Javascript 有人能解释一下这个js代码的工作原理吗;这';关键词?
JS代码是:Javascript 有人能解释一下这个js代码的工作原理吗;这';关键词?,javascript,Javascript,JS代码是: this.sound1 ="global"; function cat(){ this.sound = 'meawo!!!!'; this.sound1 = 'meawooooo!!!!'; meawo1 = function(){ console.log(this.sound1); console.log(this); }; function meawo2(){ console.log(
this.sound1 ="global";
function cat(){
this.sound = 'meawo!!!!';
this.sound1 = 'meawooooo!!!!';
meawo1 = function(){
console.log(this.sound1);
console.log(this);
};
function meawo2(){
console.log(this.sound1);
console.log(this);
};
this.meawo = function(){
console.log(this.sound);
console.log(this);
meawo1();
meawo2();
};
};
var c = new cat();
c.meawo();
输出为:
问:为什么
这个在meawo1
(函数表达式)和meawo2
(函数表达式声明)中指的是“全局”而不是对象c
?为什么会这样?当你想知道这个指的是哪个对象时,一定要记住一个简单的提示
obj.method();
在上述情况下,方法
在obj
上被调用,因此方法
中的this
将被调用,即obj=this
在您的例子中,虽然在c
上调用了meowo
,meowo1
和meowo2
不在您希望它引用的对象上
obj.method();
虽然函数本身不是全局函数,并且由于闭包,可以利用其父上下文中的所有变量,但是没有显式作用域来调用它们的函数默认为全局上下文。@我想不是。原因如果它将被提升到this.sound1='global'
的范围,那么对meawo2()的函数调用也应该在全局范围内工作,而全局范围不工作。var c
是否在函数内?还是在全球范围内?@MarkC<代码>c
在全局范围内。