“点击"和"this"在JavaScript中 [英] "onclick" and "this" in javascript
问题描述
我很困惑:
-
为什么要使用内联onlick,我们必须编写onclick ="hello()",但是在JS中,我们应该编写btn.onclick = hello或btn.addEventListener('click',hello);
why with inline onlick, we have to write onclick="hello()", but in JS, we should write btn.onclick=hello or btn.addEventListener('click',hello);
对于常规函数,为什么使用内联onlick,"this"是指窗口,但是对于js调用,"this"是指button.
for regular function, why with inline onlick, "this" refers to window, but with js call, "this" refers to button.
我不明白最后两个按钮
根据w3school,在函数中,它是指全局对象. https://www.w3schools.com/js/js_this.asp
according to w3school, In a function, this refers to the global object. https://www.w3schools.com/js/js_this.asp
在常规函数中,此关键字表示调用该函数的对象,该对象可以是窗口,文档,按钮或其他内容. https://www.w3schools.com/js/js_arrow_function.asp
In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. https://www.w3schools.com/js/js_arrow_function.asp
const arrayBtn = document.querySelector(".arrowFunc");
const regBtn = document.querySelector(".regFunc");
hello = () => console.log("i am arrow function" + this);
function hiii(){
console.log("i am regular function" + this);
}
arrayBtn.addEventListener("click", hello);
regBtn.addEventListener("click", hiii);
<button onclick="hello()">This calls an arrow function with an inline onclick</button>
<button class="arrowFunc">This calls an arrow function with event listener</button>
<button onclick="hiii()">This calls an regular function with an inline onclick</button>
<button class="regFunc">This calls an regular function with event listener</button>
<button onclick="function tes(){console.log(this)}tes()">button</button>
<button onclick="console.log(this)">button</button>
[Log] i am arrow function[object Window] <br>
[Log] i am arrow function[object Window] <br>
[Log] i am regular function[object Window] <br>
[Log] i am regular function[object HTMLButtonElement] <br>
[Log] Window {document: #document, window: Window, NaN: NaN, nalert: function, obj: {name: "my_obj"}, …} <br>
[Log] <button onclick="console.log(this)">button</button>
推荐答案
关于 this
值.
Arrow functions capture and always use their lexical
this
value, meaning the one that was in effect when their arrow function expression was evaluated. Evaluation usually occurs when executing an assignment operation or when calculating parameter values for a function call which has arrow functions in its argument list.
- 箭头函数不能用作构造函数.
使用 新
(或绑定函数保存并使用作为 bind
方法
Bound functions save and use a this value
supplied as the first argument to the bind
method of another function.
Bound functions ignore their saved
this
value if called as constructors - but this is rare enough to be considered an edge case and is not generally recommended.
绑定箭头函数对其 this
值没有影响,但可以用于预定义一组参数值.
Binding an arrow function has no effect on its this
value but could be used to predefine a set of parameter values.
使用它们的 调用
或
Functions called using either their call
or apply
object methods take their this
value from the (first) thisValue
argument supplied to call
or apply
, subject to JavaScript mode:
-
在严格模式下,为
thisValue
提供的null
或undefined
值用作函数的this
价值.在马虎模式中,null
或在拨打电话之前,将undefined
替换为window
.
In strict mode
null
orundefined
values provided forthisValue
are used as the function'sthis
value. In sloppy mode however,null
orundefined
are replaced bywindow
before making the call.
可以使用这些方法来调用箭头和绑定函数(例如,提供参数),但可以使用它们自己记录的 this
值.
Arrow and bound functions can be called using these methods (e.g. to supply arguments) but use their own recorded this
value.
未提供上述任何规则 ,显式调用为对象方法的函数将对象用作其 this
值.
E.G.以表格的形式
E.G. in a call of form
someObject.methodName( optionalArgumentList)
如果方法是常规函数,则 methodName
中的
this
引用 someObject
.
this
in methodName
refers to someObject
if the method is a regular function.
在严格模式下,未限定函数调用中的 this
的默认值为 undefined
.在草率模式下(从首次引入JavaScript时开始), this
是 window
.进行演示:
In strict mode, the default value of this
in an unqualified function call is undefined
. In sloppy mode (dating from when JavaScript was first introduced) this
is window
. For demonstration:
function a () {
"use strict";
console.log("in strict mode functions the default this is ", this);
};
let b = function() {
console.log("but in non strict mode, the default this is ",
this === window ? "window" : this
);
}
a(); // undefined
b(); // window
-
在调用全局函数构造器, <代码> SetTimeout ,相关的计时器调用和HTML源代码中的事件属性,本身就被视为脚本"并创建一个功能
Code provided as a text string in calls to the global Function constructor,
SetTimeout
, related timer calls, and event attributes in HTML source, is treated as a "script" in its own right and creates a function that
- 如果提供的源代码未调用严格模式 ,
-
将以草率模式运行
operates in sloppy mode if strict mode is not invoked by the supplied source code,
将以严格模式运行.
虽然这会更改函数的 default this
值,但这也是一种极端情况,因为在编写可维护的代码时,不建议使用这些方法来创建函数.
While this alters the default this
value of the function, is is also an edge case because none of these methods of creating a function is recommended when writing maintainable code.
The this
value when evaluating code with eval
is outside the scope of this question, but for completeness:
-
直接调用
eval
会从调用上下文中继承this
,除非所评估的代码调用严格模式-在这种情况下,this
是代码评估期间undefined
.
Direct calls to
eval
inheritthis
from the calling context unless the evaluated code invokes strict mode - in which casethis
isundefined
during code evaluation.
对 eval
的间接调用使用 window
(即全局对象)作为 this
,即使它们调用严格模式(
Indirect calls to eval
use window
(i.e. the global object) as this
even if they invoke strict mode (Ref.)
这也是一个极端情况,因为 eval
由于其危险性,应永远不要使用,因为您可以.
This is also an edge case since because of its dangers, eval
should never be used because you can.
HTML中的内联事件处理程序
HTML格式的事件处理程序内容属性
Inline event handlers in HTML
Event handler content attributes in an HTML tag of the form
onEventName="text"
由 HTML解析器使用等效于
-
将文本保存为属性的字符串值.
Save the text as the attribute's string value.
使用JavaScript解析器/编译器通过将文本包含在表单模板中来从文本创建事件处理程序函数
Use the JavaScript parser/compiler to create an event handler function from the text by including it in a template of form
function( event) {
// include attribute text here as body code
}
将函数另存为元素的属性,并与属性具有相同的名称.例如.此时,具有 onclick
文本属性的元素也将具有 onclick
属性,该属性是一个函数.
Save the function as a property of the element under the same name as the attribute. E.G. at this point an element with an onclick
text attribute will also have an onclick
property which is a function.
将函数添加到元素的内部事件处理程序映射.实际上,这意味着实际的事件处理使用侦听器映射,而不是在元素上查找处理函数.
Add the function to the element's internal event handler map. In practical terms this means actual event handling uses a map of listeners rather than looking for handler functions on the element.
警告
-
HTML onEventName属性早于DOM的标准化和
addEventListener
的引入:
处理程序具有一个旧式作用域链,该链最小限度地搜索该事件属性所属的元素,一个周围的 form
元素(如果有)以及 document
对象在查找名称时到达全局对象之前-这可能会导致模糊的错误.
Handlers created by the HTML parser have a legacy scope chain that minimally searches the element the event attribute belongs to, a surrounding form
element if any, and the document
object before reaching the global object when looking up names - which can result in obscure bugs.
问题1
为什么要使用内联onlick,我们必须编写onclick ="hello()",但是在JS中,我们应该编写btn.onclick = hello或btn.addEventListener('click',hello);
Why with inline onlick, we have to write onclick="hello()", but in JS, we should write btn.onclick=hello or btn.addEventListener('click',hello);
HTML事件处理程序属性用作HTML解析器创建的事件处理程序函数的主体代码.要调用 hello
,属性文本必须提供进行调用的源代码,例如 hello()
.
The HTML event handler attribute is used as the body code of a event handler function created by the HTML parser. To call hello
, attribute text must provide the source code to make the call, as in e.g. hello()
.
在JS中,将 onclick
设置为函数对象,或使用函数作为第二个参数调用 addEventListener
,会将函数添加到与元素.如果将括号放在函数名称之后,请使用 onclick
作为示例:
In JS, setting an onclick
to a function object, or calling addEventListener
with a function as the second parameter, adds the function to a map of handlers associated with the element. If parentheses are placed after the function name, using onclick
as an example:
onclick = myFunction();
调用该函数,并尝试将其返回值用作处理程序函数-如果返回值不是函数,则几乎不发生任何事情.通常,这是一个错误,而不是期望的结果.
问题2
the function is called and an attempt is made to use its return value as a handler function - and if the return value is not a function little happens. Most often this is a mistake and not the desired outcome.
question 2
对于常规功能,为什么在嵌入式onclick中,"this"是指窗口,而在js调用中,"this"是指按钮.
For regular function, why with inline onclick, "this" refers to window, but with js call, "this" refers to button.
在通过内联onclick属性创建的事件处理函数中, this
确实引用该按钮.如果使用诸如 hello()
之类的代码调出另一个函数,则您将对其进行无限定的调用,因此被调用函数将使用其默认的 this
值-即 window
(如果调用的函数在草率模式下运行).
Inside the event handler function created from an inline onclick attribute, this
does refer to the button. If you call out to another function with code like hello()
, you are making an unqualified call to it, so the called function uses its default this
value - i.e. window
if the called function operates in sloppy mode.
接着"HTML内联事件处理程序",您可以传递 this
(指按钮)和 event
对象作为参数值,如果您想:
Following on from "Inline event handlers in HTML", you could pass on this
(referring to the button) and the event
object as a parameter values if you wanted to:
onclick="hello(this, event)"
JavaScript中提供的
Handler函数直接进入事件处理程序的元素映射,并由事件系统使用按钮将其作为 this
值(可能使用 call
或 apply
,因为添加了 addEventListener
的处理程序不会保留为元素属性值.
Handler functions provided in JavaScript go directly into the element's map of event handlers and are called by the event system with the button as their this
value (probably using call
or apply
, since handlers added with addEventListener
aren't maintained as element property values).
问题3
< button onclick ="function tes(){console.log(this)} tes()"> button>/button>
创建事件处理函数
function onclick(event) {
function tes(){
console.log(this)
}
tes()
}
在按钮标签的事件属性文本中未调用严格模式,因此 onclick
和 tes
均处于草率模式.调用 tes
是无条件的,因此它使用并记录其默认 this
值,即 window
.
Strict mode was not invoked in the button tag's event attribute text, so both onclick
and tes
are in sloppy mode. tes
is called without qualification, so it uses and logs its default this
value which is window
.
关于大约这个值",第1-5条都不适用,因此第6条生效.
In regards to "about this values", none of rules 1 - 5 apply, so rule 6 comes into effect.
问题4
< button onclick ="console.log(this)"> button</button>
创建处理程序函数
function onclick(event) {
console.log(this)
}
与事件处理程序一样,事件系统使用按钮元素作为其 this
值调用的
. console.log
在日志中显示按钮的外部HTML.如果将 this
更改为字符串,日志将改为告诉您其HTMLButtonElement元素:
which is called with the button element as its this
value by the event system as it would for any other handler. console.log
is showing the outer HTML for the button in the log. If you change this
to a string, the log will tell you its an HTMLButtonElement element instead:
<button onclick="console.log(this.toString())">button</button>
这篇关于“点击"和"this"在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!