标签:style blog io color ar os java sp div
《javascript高级程序设计》的摘抄
Ps:很好的一本书,大家可以直接去看书,这里只是记录。推荐一个计算机电子书网站: 皮皮书屋
查资料:MDN,W3CSCHOOL,google
this:函数的调用方式决定了this的值
----在Global context 全局上下文
指向window,“use strict”模式下指向undefined
---------------------------
一句话,this由所在运行时上下文环境决定,运行时上下文环境是谁,this就指向谁
function a( ){ return this }
a函数是在全局环境下
a() //等价与下面
window.a()
所以this指向window
------------
var name= "The Window"; var object ={ name: "My Object", getNameFunc: function(){ return function(){ return this.name; //匿名函数,闭包 }; } }; alert(object.getNameFunc()()); //The Window
object.getNameFunc()返回的是匿名函数,因为匿名函数的执行环境具有全局性,所以this指向window
-------------------
var name= "The Window"; var object ={ name: "My Object", getNameFunc: function(){
var that =this return function(){ return that.name; //匿名函数,闭包 }; } }; alert(object.getNameFunc()()); //The Object
var that = this ,this是object环境中的,所以this指向object,这很明显,所以that.name也是指向object.name
----------------
var o = {prop: 37}; function independent() { return this.prop; } o.f = independent; //o.f =window.independent 指向同一函数,但运行时不同,一个是o,一个是window console.log(o.f()); // logs 37
//等价于
var o = {prop: 37};
o.f = function(){
return this.prop
}
console.log(o.f()); // logs 37
所以很明显this是在o的环境中,所以this指向o
--------------------------
var name= "The Window"; var object ={"name": "My Object"}; console.log( (object.getName=function(){ //匿名函数赋值,并执行,所以指向window return this.name; })() ); //This Window console.log(object.getName()); //My object
有种C指针的感觉,脑子里是一个个有向的箭头,想箭头的另一端,就知道this指向谁了
---------------------------------------------------------------------------------------------------------------
1 var name = "The Window";
2
3 var object = {
4 name: "My object",
5 getName: function(){
6 return this.name
7 }
8 }
9 (object.getName = object.getName)( ); //The Window
Uncaught TypeError: Cannot read property ‘getName‘ of undefined
而IE11下没问题,为什么????
标签:style blog io color ar os java sp div
原文地址:http://www.cnblogs.com/X-chen/p/yexiaochai.html