《悟透JavaScript》学习札记六之放下对象
来源:互联网 发布:mac游戏加速器 编辑:程序博客网 时间:2024/05/01 20:12
function WhoAmI()
{
alert("I'm " + this.name + " of " + typeof(this));
};
WhoAmI(); // output: I'm of object
// 此时this是根对象window,其name属性为空字符串
var Bill = {name: "Bill"};
Bill.WhoAmI = WhoAmI; // 将函数WhoAmI作为BillGates的方法。
Bill.WhoAmI(); // this是Bill,output: I'm Bill of object
var Sam = {name: "Sam"};
Sam.WhoAmI = WhoAmI;
Sam.WhoAmI(); // output: I'm Sam of object
WhoAmI.call(Bill); //output: I'm Bill of object
WhoAmI.call(Sam); // output: I'm Sam of object
Bill.WhoAmI.call(Sam); // 将Sam作为this,却调用Bill的方法。output: I'm Sam of object
Sam.WhoAmI.call(Bill); // 将Bill作为this,却调用Sam的方法。output: I'm Bill of object
WhoAmI.WhoAmI = WhoAmI; // 将WhoAmI函数设置为自身的方法。
WhoAmI.name = "WhoAmI";
WhoAmI.WhoAmI(); // 此时的this是WhoAmI函数自己。output: I'm WhoAmI of object
({name: "nobody", WhoAmI: WhoAmI}).WhoAmI(); // 创建一个匿名对象并调用其方法。output: I'm nobody of object
以上代码可以看出,this并不一定是函数本身所属的对象。在JavaScript函数中,你只能把this看成当前要服务的“这个”对象。在一般对象语言中,方法体代码中的this可以省略,成员默认都首先是“自己”的。但JavaScript却不同,由于不存在“自我”,当访问“这个”对象时,this不可省略。
注:self属性表示网页结构的当前window对象,以及frame或iframe元素的window对象。
- 《悟透JavaScript》学习札记六之放下对象
- 《悟透javascript》学习笔记:六、放下对象
- 悟透JavaScript之放下对象 -- 1
- 悟透JavaScript之放下对象 -- 2
- 悟透JavaScript-放下对象
- 悟透JavaScript - 放下对象
- 《悟透JavaScript》学习札记五之奇妙的对象
- 《悟透JavaScript》学习札记七之对象素描
- 《悟透JavaScript》学习札记八之构造对象
- 《悟透JavaScript》学习札记之标准网页
- 《悟透JavaScript》学习札记一之回归简单
- 《悟透JavaScript》学习札记二之没有类
- 《悟透JavaScript》学习札记三之函数的魔力
- 《悟透JavaScript》学习札记九之初看原型
- 《悟透JavaScript》学习札记十之原型扩展
- 《悟透JavaScript》学习札记十一之原型真谛一
- 《悟透JavaScript》学习札记十一之原型真谛二
- 《悟透JavaScript》学习札记之响应DOM事件
- 原码、反码、补码总结
- dbm1
- 测试人员价值体现
- 嵌入式文件系统
- hibernate 中createQuery与createSQLQuery
- 《悟透JavaScript》学习札记六之放下对象
- Install error "Exit Code: 6" or "Exit Code: 7" | Creative Adobe Production(安装Adobe产品时出错及解决方案)
- 名言
- 用两个atmega48(或atmega8)制作的通用编程器
- c++位运算
- 标记化结构初始化语法 在结构体成员前加上小数点 如 “.open .write .close ”C99编译器
- 我的Emacs配置(.emacs 和 load-files.el) -- 001
- hdu3861 The King’s Problem
- 对中断的一点理解