标签:query pen code cti ace block str 数列 mono
this
keyword的使用
在JavaScript中使用this
keyword表示调用方法的对象,这与大部分面向对象语言是一样的。可是因为call
、apply
、bind
等函数的影响。我们能够改变this
所代指的对象。
call
或者apply
调用的函数中,this
代指传入的第一个參数对象,假设传入null
或者undefined
。则表示全局对象(window
)。this
表示调用该函数的对象。this
表示全局对象。var myObject = {
sayHello: function() {
console.log("Hi, my name is " + this.myName);
},
myName: "Rebecca"
};
var secondObject = {
myName: "Colin"
};
myObject.sayHello(); //"Hi, my name is Rebecca"
myObject.sayHello.call(secondObject); //"Hi, my name is Colin"
var myName = "the global object";
var sayHello = function() {
console.log("Hi, my name is " + this.myName);
};
var myObject = {
myName = "Rebecca"
};
var myObjectHello = sayHello.bind(myObject);
sayHello(); //"Hi, my name is the global object"
myObjectHello(); //"Hi, my name is Rebecca"
JavaScript能够在执行中为对象动态加入函数,这样也会导致this
代指的对象发生变化。
var myName = "the global object";
var sayHello = function() {
console.log("Hi, my name is " + this.myName);
};
var myObject = {
myName: "Rebecca"
};
var secondObject = {
myName: "Colin"
};
myObject.sayHello = sayHello;
secondObject.sayHello = sayHello;
sayHello(); //"Hi, my name is the global object"
myObject.sayHello(); //"Hi, my name is Rebecca"
secondObject.sayHello(); //"Hi, my name is Colin"
还有。不能直接给处于较深的名字空间的函数添加短引用,会导致this
变为全局对象,可是能够对它所处的对象设置短引用。
var myNamespace = {
myObject: {
sayHello: function() {
console.log("Hi, my name is " + this.name);
},
myName: "Rebecca"
}
};
var hello = myNamespace.myObject.sayHello;
hello(); //"Hi, my name is undefined"
var obj = myNamespace.myObject;
obj.sayHello(); //"Hi, my name is Rebecca"
Tips
call
与apply
的差别是,apply
接收两个參数:this
和函数的參数数组;而call
的第一个參数为this
,可是后面是函数的參数列表。本文档由长沙戴维营教育整理。
Jquery第四课 Javascript中this的使用方法
标签:query pen code cti ace block str 数列 mono
原文地址:http://www.cnblogs.com/gavanwanggw/p/6848718.html