当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 如何使用Javascript中的this关键字

如何使用Javascript中的this关键字

2020年06月14日  | 移动技术网IT编程  | 我要评论

一、基本的:

function dosomething(){
alert(this.id);
}
alert(window.dosomething);//证明了dosomething是属于window的
dosomething();//undefined
window.onload = function(){
document.getelementbyid("div2").onclick = dosomething;//div2
document.getelementbyid("div3").onclick = function(){dosomething();}//undefined
} 

1、对于dosomething这个函数:

function dosomething(){
alert(this.id);
}

这个函数是全局函数,这种全局函数实际上是属于window的(可以通过window.dosomething来访问),如果直接调用,那么根据“this always refers to the “owner” of the function we're executing”,那么函数中的this就是window,但是window没有id属性,所以显示“undefined”;

2、在html元素中这样调用

<div id="div1" onclick="dosomething();">div1</div> 

这时也会显示“undefined”,这就相当于如下代码:

document.getelementbyid("div1").onclick = function(){dosomething();} 

当点击div1时,调用属于window的dosomething函数,所以也是显示“undefined”;

3、通过js来绑定事件,在div2载入过后:

document.getelementbyid("div2").onclick = dosomething; 

当点击div2时,显示“div2”,因为在给div2的onclick赋值,是将dosomething拷贝了一次,这时拷贝的这个函数是属于div2的了,跟属于window的dosomething没有任何关系了。点击div2时,就会触发属于div2的dosomething,这里的this就是指div2。

二、attachevent和addeventlistener 

attachevent是在ie中绑定事件的方法,会将相应函数拷贝到全局(即响应函数的owner为window),但是在dom标准中,addeventlistener绑定的事件时拷贝的响应函数的owner为事件所绑定的对象

function dosomething(){
alert(this.id);
alert(this == window);
}
window.onload = function(){
var div1 = document.getelementbyid("div1");
if(div1.attachevent){
div1.attachevent("onclick",dosomething);
document.body.appendchild(document.createtextnode("attachevent"));
}else if(div1.addeventlistener){
div1.addeventlistener("click",dosomething,false);
document.body.appendchild(document.createtextnode("addeventlistener"));
}else{
div.onclick = dosomething;
}
} 

对于函数dosomething

function dosomething(){
alert(this.id);
alert(this == window);
} 

1、使用attachevent绑定到div1的click事件上,dosometing会被复制到window,这时dosomething里面的this指的是window,点击div1时会显示“undefined”和“true”

2、使用addeventlistener绑定div1的click事件,这时将dosomething拷贝,这个拷贝过后的函数是属于div1的,所以点击div1时会显示“div1”和“false”,看如下代码

var obj = new object();
obj.color = "black";
obj.showcolor = function(){
alert(this.color);
alert(this == window);
}
obj.showcolor();

var div1 = document.getelementbyid("div1");
div1.attachevent("onclick",obj.showcolor); 

此时点击div1的时候,会显示“undefined”和“true”,如果attachevent仅仅是引用obj.showcolor的话,那么this还是应该指的是obj,但是实际上这里this指的是window,所以我认为这里不是引用,而是拷贝到全局的。

三、关于对象冒充的继承方式 

1、new与不new的区别

对于如下function

function classa(scolor){
this.color = scolor;
this.saycolor = function(){
alert(this.color);
}
} 

这是一个类还是一个函数?随你而定!

如果你认为这是一个函数,那么我们可以这样来调用它:

classa("red");

“red”是传递的一个参数,classa中的this指的是当然就是指的window了,所以现在window有了color属性和saycolor方法,并且color有“red”这个值。

这是调用saycolor或者window.saycolor都可以显示“red”;

window.saycolor();

如果你认为这是一个类,那么我们应该这样使用它:

var obj = new classa("red");

new这个关键词的出现让上面这一句代码增加了不少内容:首先,创建一个object实例,然后,将classa中的this指向创建的这个object中,最后返回这个object,所以返回的这个object就赋值给了obj。所以我们可以说this指向的是obj,obj拥有了color属性和saycolor方法,并且color属性值为“red”。

2、函数的owener

function showid(){
alert(this.id);
}
window.onload = function(){
var div1 = document.getelementbyid("div1");
div1.onclick = showid;
div1.show = showid;
div1.show();

var obj = new object();
obj.id = "obj";
obj.show = showid;
obj.show();
} 

我们可以将showid这个函数赋值给click事件,也可以赋值给任何一个对象的任何一个属性,这是也会拷贝showid这个方法的,所以我们在调用div1.show方法时,this是指向div1的,在调用obj.show时,this指向的是obj的。

3、对象冒充的原理

下面的代码是通过对象冒充方法实现的继承

function classa(scolor){
this.color = scolor;
this.saycolor = function(){
alert(this.color);
}
}

function classb(scolor,sname){
this.newmethod = classa;
this.newmethod(scolor);
delete this.newmethod;

this.name = sname;
this.sayname = function(){
alert(this.name);
}
}

var objb = new classb("color of objb","name of objb");
objb.saycolor(); 

objb是classb的一个实例,objb是如何拥有color属性和saycolor方法的呢?

首先从实例化的代码看起:

var objb = new classb("color of objb","name of objb");

这里classb是个类,classb中的this当然就是指的objb这个对象;

在classb中,前三行代码会用到classa,这时就把classa看作一个函数,而不是类。

我们如果直接调用classa这个函数,那么很显然,classa中的this指的就是window对象了,所以我们先将classa拷贝到objb的newmethod这个属性中(this.newmethod = classa),

然后再调用this.newmethod,这是这个方法的owener明显的已经成了this,而classb中的this在当前指的是objb,所以此时classa中(严格的说是newmethod中,因为这是拷贝过后的,跟classa已经是两个方法了)的this就是指的objb,这样在通过newmethod的调用,就给objb赋值了color属性和saycolor方法。用call和apply方法来实现继承实际上也是一个原理,call和apply可以看作是改变方法的owner的方法,而这里classb中的前三句代码也就是起这个作用的。

四、prototype1.6中的class.create

prototype1.6中的class.create方法大致如下:

var class = {
create: function() {
//

function klass() {
this.initialize.apply(this, arguments);
}

//

for (var i = 0; i < properties.length; i++)
klass.addmethods(properties[i]);

//

return klass;
}
}; 

在使用的时候是这样的:

var person = class.create({
initialize:function(name){
this.name = name;
},
say:function(message){
alert(this.name + ":" + message);
}
});

var aperson = new person("name1");
aperson.say("hello1"); 

person实际上是通过class.create这个方法所返回的klass(klass是class.create中的局部变量,是一个function),class.create所传递的参数(initialize方法和say方法)传递到create方法中的properties数组中并且通过addmethods方法让klass的prototype拥有这些方法。那么最关键的地方也是最难以理解的地方是:klass中的this究竟是指的是什么。仔细想一想就不难得到答案,person实际上就是klass,而我们在实例化person对象的时候,是用了new关键词的:

var aperson = new person("name1");

这就等价于

var aperson = new klass("name1");

虽然klass在外面不能被访问到,但是这样能很轻易的说明问题,klass是一个类而不是简单的一个函数(我们看作如此,因为用了new关键字),那么klass中的this就指的是声明的实例,在这里就是aperson,aperson通过klass的prototype能够拥有initialize方法和say方法,在new的过程中,也会执行klass中的代码,所以initialize在实例化的时候会执行,即构造函数。(在klass里两个this都是指的aperson,为什么还要通过apply调用一次呢?这主要是为了传递构造函数的参数,用apply方法可以将数目不定的多个参数通过数组方便的传到initialize方法中去。)

五、再分析几个例子

从别的文章里看到的例子,我在这里分析一下:

1、运行如下代码

function outerfoo(){
this.name = 'outer name';

function innerfoo(){
var name = 'inner name';
alert(name + ', ' + this.name);
}
return innerfoo;
}
outerfoo()(); 

所显示的结果是“inner name, outer name”

outerfoo是一个函数(而不是类),那么第一句

this.name = 'outer name';

中的this指的是window对象,所以outerfoo()过后window.name = ‘outer name';

并且将innerfoo返回,此时innerfoo同样是一个函数(不是类),执行innerfoo的时候,this同样指window,所以innerfoo中的this.name的值为”outer name”(window.name充当了一个中转站的角色,让outerfoo能够向innerfoo传递“outer name”这个值),而name的值即为局部变量”inner name”

2、运行如下代码

function jsclass(){

this.m_text = 'division element';
this.m_element = document.createelement('div');
this.m_element.innerhtml = this.m_text;

if(this.m_element.attachevent)
this.m_element.attachevent('onclick', this.tostring);
else if(this.m_element.addeventlistener)
this.m_element.addeventlistener('click', this.tostring,false);
else
this.m_element.onclick = this.tostring;
}

jsclass.prototype.render = function(){
document.body.appendchild(this.m_element);
}

jsclass.prototype.tostring = function(){
alert(this.m_text);
alert(this == window);
}

window.onload = function(){
var jc = new jsclass();
jc.render();
jc.tostring();
} 

点击“division element”会显示“undefined”,在ie下还要显示“true”,其他浏览器中还要显示“false”。

实例声明和调用实例方法都没什么可说的,元素的click事件的绑定到了一个实例的方法,那么通过addeventlistener绑定到的方法是拷贝过后的,所以this指的是html元素,这个元素没有m_text属性(m_text属性是属于jsclass的实例的,即属于jc的),所以点击元素显示undefined,attachevent绑定的事件会将函数复制到全局,此时this指的是window对象,点击元素也会显示“undefined”。只有在调用jc.tostring()方法是,this指的是jc这个对象,因为jc拥有m_text,所以能够显示“division element”。

六、总结

怎样在一个代码环境中快速的找到this所指的对象呢?我想要注意以下三个方面:

1、 要清楚的知道对于函数的每一步操作是拷贝还是引用(调用)

2、 要清楚的知道函数的拥有者(owner)是什么

3、 对于一个function,我们要搞清楚我们是把它当作函数使用还是在当作类使用

补充:

1.在实例和类上都可以直接定义函数

2.不能在实例上使用prototype定义函数,只能在类上使用prototype定义函数

3.类上直接定义的函数不能使用this访问对象的属性

4.在类的prototype上建立的函数可以用this,在类内部定义的函数可以使用this,在对象实例上建立的函数额可以this

window.alert=function (msg)
{
document.write(msg+"<br>");
}
function say()
{
this.f="props";
this.func3=function(){alert("f3,"+this.f);}
}
say.func1=function(){alert("func1,"+this.f);}; //error,类上直接定义的函数,不能使用this
say.prototype.func2=function(){alert("func2,"+this.f);}
say.func1();
(new say()).func2();
say.func2(); //error, 在用prototype定义的函数,必须实例化对象才能调用
say.func3(); //error,在类上定义的函数,必须实例化才能调用
(new say()).func3();
var obj={
fld1:10,
func1:function(msg){alert(msg);},
func4:function(){alert(this.fld1);}
}
obj.prototype.func=function(){alert("func");}; //error 实例对象上不能使用prototype定义对象
obj.func2=function(){alert("func2,"+this.fld1);}; //ok,实例上直接定义的函数可以使用this,访问对象的属性
alert(obj.fld1);
obj.func1("func1");
obj.func2();
obj.func4();

以上就是如何使用javascript中的this关键字的详细内容,更多关于js this关键字的资料请关注移动技术网其它相关文章!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网