this的值
2015-08-09 17:01
204 查看
在面向对象的编程中,this值很重要,且它的值取决于调用的模式
方法调用模式:this被绑定到该对象
函数调用模式:this被绑定到全局对象
解决办法为
构造器调用模式:在函数前面使用new来调用,会创建连接到该函数的prototype属性的新对象,this会绑定到这个新对象上
Apply/Call调用模式:函数拥有这两个方法,允许我们选择this的值
总结:在调用函数时,对参数this及arguments的搜索不遵守作用域链规则
方法调用模式:this被绑定到该对象
var name = "outer"; var myObj = { name : "inner", getName : function () { return this.name; } }; console.log(myObj.getName()); //inner,this指向myObj
函数调用模式:this被绑定到全局对象
var name = "outer"; var myObj = { name : "inner", getName : function () { return function(){ return this.name; }; } }; console.log(myObj.getName()()); //outer,this指向window
解决办法为
var name = "outer"; var myObj = { name : "inner", getName : function () { var that = this; return function(){ return that.name; }; } }; console.log(myObj.getName()()); //inner
构造器调用模式:在函数前面使用new来调用,会创建连接到该函数的prototype属性的新对象,this会绑定到这个新对象上
function Dog (color) { this.color = color; } Dog.prototype.getColor = function (){ return this.color; }; var dog = new Dog("yellow"); //this绑定到dog上 console.log(dog.getColor()); //yellow
Apply/Call调用模式:函数拥有这两个方法,允许我们选择this的值
var name = "outer"; var myObj = { name : "inner", getName : function () { return this.name; } }; console.log(myObj.getName()); //inner,this指向myObj console.log(myObj.getName.apply(window)); //outer,this指向window
总结:在调用函数时,对参数this及arguments的搜索不遵守作用域链规则
相关文章推荐
- Shuffle'm Up 分类: 函数 POJ 查找 2015-08-09 17:01 6人阅读 评论(0) 收藏
- ThinkPHP- 3.1
- ActionScript 3.0 学习(五) AS3 Losder加载图片以及显示对象遮罩介绍
- Python 实现简单的电话本功能
- HDU 5237 Base64 (Java大法好)
- POJ-1606 Jugs
- LeetCode #3 Longest Substring Without Repeating Characters
- Oracle并行
- 华为OJ(杨辉三角变形)
- android--onLayout源码 流程 思路详解
- HDOJ1021
- ssh 对集成hibernate测试
- 装好MYsql后显示Access denied for user 'root'@'localhost' (using password: NO)
- 1.5 创建分区
- Linux - 有效群组(effective group)与初始群组(initial group),groups,newgrp
- Linux - 有效群组(effective group)与初始群组(initial group),groups,newgrp
- 【已解决】Python脚本运行出现语法错误:IndentationError: unindent does not match any outer indentation level
- Linux内核驱动并发控制
- HHD+SSD重装mac os 10.9记录
- Android基于GridView实现的翻牌游戏效果