本篇文章给大家分享的是有关如何在javascript中使用this,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
实践一:this在点击等事件中的指向
html结构:
<button id='btn'>click me</button>
javascript结构:
var btn = document.getElementById('btn');
btn.onclick = function(event) {
console.log(this.innerHTML); // click me
// 还有另一种做法如下,用事件对象
var evt = event || window.event;
var target = evt.target || evt.srcElement;
console.log(target.innerHTML); // click me
}
实践二:this在对象字面量json中的指向,指向自身对象
var p = {
"name":"Tom",
"say":function(){
console.log(this.name + ' say something!');
}
}
p.say(); // Tom say something!
实践三:this在全局作用域中的使用
var a = 1;
console.log(this); // window
console.log(this.a); // 1
function test(){
console.log(this); // window
this.haha = 'i am haha';
};
test(); // 函数一执行,haha 作用域变成全局的
console.log(haha); // i am haha
实践四:this在定时器中的指向,定时器是window对象的一个方法,定时器中的this指向window对象,setTimeout()
和 setInterval()
是一样的
var div = document.getElementById('div');
div.onclick = function() {
var that = this; // 用that 来存储当前的div这个dom元素
setTimeout(function(){
console.log(this + ' i am this'); // [object Window] i am this
console.log(that + ' i am that'); // [object HTMLDivElement] i am that
}, 100);
}
实践五:this在对象中的指向,指向当前实例对象
function Person(){
this.name = 'jack';
};
Person.prototype = {
buy:function() {
console.log(this.name + ' go buy!');
}
}
var p = new Person();
console.log(p.name); // jack;
p.buy(); // jack go buy!
实践六:this在闭包中的应用1
var age = 20;
var person = {
"age" : 10,
"getAgeFunc" : function(){
return function(){
return this.age; // this 指向 window
};
}
};
console.log(person.getAgeFunc()()); // 20
/*
分析这段代码:person调用getAgeFunc() 在内存中返回一个函数,这个函数是全局的,然后加个() 执行。那么,返回20
*/
实践七:this在闭包中的应用2
var age = 20;
var person = {
"age" : 10,
"getAgeFunc" : function(){
var that = this;
return function(){
return that.age; // that 指向 person
};
}
};
console.log(person.getAgeFunc()()); // 10
/*
分析这段代码:person调用getAgeFunc() 用that代替当前对象,当执行返回的闭包函数时,age是person对象的一个属性那么,返回10
*/
实践八:用call和apply改变this的指向 ,以后会详细分析 call和apply以及闭包的概念
var person = {
"name":"Tom",
"say":function(x,y) {
console.log(this.name + ' say ' + x + ' ' + y);
}
}
var student = {
"name":"Lucy"
}
person.say.call(student,'hello','world'); // Lucy say hello world
person.say.apply(student,['hello','javascript']); // Lucy say hello javascript
以上就是如何在javascript中使用this,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。