首先我们需要知道,function的invoke方式主要有三种:1、单纯调用 2、作为某对象的method被调用 3、apply()和call()调用。针对三种不同的invoke方式,"this"拥有不同的指向:当function被作为单纯的function启动时,那么“this”指向的是global object;当function是某个object的method,并由该object作为方法来启动时,“this”指向调用该function的那个object;使用apply()和call()方法调用时,function中的"this"指向的是这两个方法中的作为第一个参数的那个对象。
1. ordinary invoke
var testVar = 20;
function test() {
var testVar = 40;
document.write (this.testVar); // 20 is printed,"this" refers to global object
}
test();
2. method invoke
var testVar = 20;
function test() {
var testVar = 30;
var o = {testVar: 60,
methodFunc: function(){
this.testVar = 70; //when the function invoked, “this” refers to o
}};
o.methodFunc();
document.write(testVar + "<br>"); //print 30
document.write(o.testVar + "<br>"); //print 70, property of o has been changed
document.write(this.testVar + "<br>"); //print 20, property of global object remains as
}
test();
3. nested function in a method---ordinary invoke
var testVar = 20;
function test5() {
var testVar = 30;
var o = {testVar: 60,
methodFunc: function(){
this.testVar = 70;
(function(){
this.testVar = 40;
})();
}};
o.methodFunc();
document.write(testVar + "<br>"); //30
document.write(o.testVar + "<br>"); //70, this refers to object o
document.write(this.testVar + "<br>"); //40, this refers to global object !!!!Confusing ha? But it's true!!!
}
test5()
4. invoked by call() and apply()
function bindedFunc() {
this.testVar = 40;
}
function test() {
var testVar = 20;
var o = {testVar: 30};
bindedFunc.apply(o);
document.write(o.testVar) //prints 40
}
test();
分享到:
相关推荐
JavaScript_——DOM总结.txt
用JavaScript绘图 ——JS2D函数集
《javascript》——event对象与事件
javascript运算符——位运算符全面介绍.docx
Really JavaScript!——Douglas Crockford大师见面会报道.pdf
浅谈JavaScript库——jQuery,ExtJs的对比研究.pdf
小议JavaScript库——Dojo、jQuery和PrototypeJS的比较.pdf
博文链接:https://fuhao9611.iteye.com/blog/72257
浅谈javascript运算符——条件,逗号,赋值,()和void运算符_.docx
JavaScript凌厉开发——Ext详解与实践 源码 源代码 part3 因为源代码比较大,压缩后76M左右 所以分为四个包上传
javascript——PDF教程大合集 1、100个直接可以拿来用的JavaScript实用功能代码片段 2、JavaScript DOM编程艺术(中文) 3、JavaScript高级程序设计(第3版)中文 高清 完整 4、JavaScript脚本特效编程给力起飞 5、...
用JavaScript实现的邮箱格式验证
javascript实战 图灵系列 分成四个压缩包,用好压解压,这是第一个
javascript实战 图灵系列 第三卷
NULL 博文链接:https://hrsvici412.iteye.com/blog/337605
javascript实战 图灵系列 这是第二卷
javascript实战 图灵系列 这是第四卷
本文简单介绍了目前流行的JavaScript 库, 并对其中较为流行的两个库jQuery 和ExtJs 进行的较详细的介绍和对比研究, 对在 Web 开发中JavaScript 库的选择具备一定的参考价值。