Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 有人能解释一下这个js代码的工作原理吗;这';关键词?_Javascript - Fatal编程技术网

Javascript 有人能解释一下这个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(

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);
        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
在全局范围内。