javascript中的this分析

来源:互联网 发布:手机工程算量软件 编辑:程序博客网 时间:2024/05/22 08:18

实践一: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); // windowconsole.log(this.a); // 1function 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 worldperson.say.apply(student,['hello','javascript']); // Lucy say hello javascript

0 0
原创粉丝点击