一、在一般函数方法中使用this指代全局对象 function test(){ this、x = 1; alert(this、x); } test(); // 1 二、作为对象方法调用,this指代上级对象 func
function test(){
this、x = 1;
alert(this、x);
}
test(); // 1
function test(){
alert(this、x);
}
var o = {};
o、x = 1;
o、m = test;
o、m(); // 1
function test(){
this、x = 1;
}
var o = new test();
alert(o、x); // 1
//运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变:
var x = 2;
function test(){
this、x = 1;
}
var o = new test();
alert(x); //2
apply方法作用是改变函数的调用对象,此方法的名列前茅个参数为改变后调用这个函数的对象,this指代名列前茅个参数
var x = 0;
function test(){
alert(this、x);
}
var o={};
o、x = 1;
o、m = test;
o、m、apply(); //0
在对象方法中,this指的是此方法的“拥有者”。
this代表person对象
var person = {
firstName:”Bill”,
lastName:”Gates”,
id:678,
fullName:function(){
return this、firstName + ” ” + this、lastName;
}
};
(1)在单独使用时,拥有者是全局对象,this指的是全局对象
在浏览器窗口中,全局对象是[object Window]:
var x = this;
document、getElementById(“demo”)、innerhtml = x;
(2)在严格模式中,如果单独使用,那么this指的是全局对象[object Window]:
“use strict”;
var x = this;
在js函数中,函数的拥有者默认绑定this、
因此,在函数中,this指的是全局对象[object Window]
function myFunction(){
return this;
}
js严格模式不允许默认绑定,因此,在函数中使用时,在严格模式下,this是未定义的undefined
“use strict”;
function myFunction(){
return this;
}
this指的是html元素,如下面例子中,this指的是button
<button onclick = “this、style、display=’none’”>
点击来删除我!
</button>
--结束END--
本文标题: JS中的this是用来干什么的
本文链接: https://www.lsjlt.com/news/521186.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0