简体   繁体   English

JavaScript 原型范围问题

[英]JavaScript prototype scope issue

I'm new to JavaScript so I apologize if it's too dumb question.I don't understand how this keyword behaves in examples below.我是 JavaScript 新手,所以如果问题太愚蠢,我深表歉意。我不明白this关键字在下面的例子中是如何表现的。

In first case, this refers to window object:在第一种情况下, this指的是window对象:

Element.prototype.x = this;
some_element.x; // Returns window object.

And in second, it refers to DOM Element:其次,它指的是 DOM 元素:

Element.prototype.x = function(){return this;};
some_element.x(); // Returns element itself.

Why?为什么? How do those examples differ?这些例子有何不同?

In first case, this refers to window object:在第一种情况下,这指的是 window 对象:

Element.prototype.x = this; ( Here the scope points to window "Global scope in js" ) (这里的范围指向窗口“js中的全局范围”)

And in second, it refers to DOM Element:其次,它指的是 DOM 元素:

Element.prototype.x = function(){return this;}; ( But where as here You are defining a function to the Object "Element", so the scope of this keyword is pointing "Element" Object. ) (但是在这里,您正在为对象“元素”定义一个函数,因此此关键字的范围指向“元素”对象。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM