在javascript 中this 的定义:包含它的函数被调用时,所属的对象。
例子b:
在例子b中,我用的new test()进行test调用,那么这次呢?这句话的意思是新建一个 test函数对象并且执行它,显然是test 的原型也就是test本身调用了(执行了)自己,此
这句话非常简练精准!
1. 首先this是一个对象!
2. 其次,this的值是变化的,包含它的函数被调用时所属的对象,随着该函数被不同的对象调用,this也就不同了。
请看以下例子:
例子a:
function init(){
console.log('this is windows init!');
}
function test(){
var init=function(){console.log('this is test init!');};
this.init();
}
test();
输出:this is windows init!
大家可以看到,我在window中直接调用了test函数,所以test函数此时属于window对象,this=window!那么this.init就是在window中直接定义的 function init 了;所以输出的是' this is windows init ! '
例子b:
function init(){
console.log('this is windows init!');
}
function test(){
var init=function(){console.log('this is test init!');};
this.init();
}
test.prototype={init:function(){console.log('this is test prototype init!')}};
new test();
输出:this is test prototype init!
在例子b中,我用的new test()进行test调用,那么这次呢?这句话的意思是新建一个 test函数对象并且执行它,显然是test 的原型也就是test本身调用了(执行了)自己,此
时,test函数中的this就是test的本身或者说是他的原型,那么 this.init = test.prototype.init 了,也就是输出了 ’ this is test prototype init! ‘ .
好了,今天就理解了这么多,下次接着学习!
路漫漫啊!