js this object
来源:互联网 发布:微信拓客软件怎么用 编辑:程序博客网 时间:2024/05/29 03:02
function showColor() { alert(this.color
);};var oCar1 = new Object;oCar1.color = "red";oCar1.showColor = showColor;var oCar2 = new Object;oCar2.color = "blue";oCar2.showColor = showColor;oCar1.showColor();//输出 "red"oCar2.showColor();//输出 "blue"
TIY
在上面的代码中,首先用 this 定义函数 showColor(),然后创建两个对象(oCar1 和 oCar2),一个对象的 color 属性被设置为 "red",另一个对象的 color 属性被设置为 "blue"。两个对象都被赋予了属性 showColor,指向原始的 showColor () 函数(注意这里不存在命名问题,因为一个是全局函数,而另一个是对象的属性)。调用每个对象的 showColor(),oCar1 输出是 "red",而 oCar2 的输出是 "blue"。这是因为调用 oCar1.showColor() 时,函数中的 this 关键字等于 oCar1。调用 oCar2.showColor() 时,函数中的 this 关键字等于 oCar2。
注意,引用对象的属性时,必须使用 this 关键字。例如,如果采用下面的代码,showColor() 方法不能运行:
function showColor() { alert(color
);};
call() 方法是与经典的对象冒充方法最相似的方法。它的第一个参数用作 this 的对象。其他参数都直接传递给函数自身。
apply() 方法有两个参数,用作 this 的对象和要传递给函数的参数的数组。
对象冒充可以支持多重继承。
- js this object
- JS:what is this "Object.prototype" anyway...?
- js中的this & var, function & object, prototype & apply
- jquery&js $(this) & this
- js Object
- js object
- js: Object
- js this
- JS this
- JS this
- js this
- js this
- js this
- js this
- JS this
- [js] this
- js--this
- js--this
- C语言中的#undef
- ubuntu flash插件安装
- Linkedin网站技术架构简介
- 04 ImageView中图片保存到文件
- Hadoop十大应用领域--从互联网行业到传统行业
- js this object
- centos 6.4安装subversion-1.7.9记录
- 程序员杂谈
- 我是怎么招聘程序员的
- QtCreator插件开发之学习日记1
- PB调用WebService_1
- opencv之金字塔实现图像分割
- PB调用WebService_2
- PB调用WebService遇到的问题