前端学习(九)关于this关键字的理解
2017-08-14 16:06
253 查看
JavaScript的关键字 this,函数运行时,自动生成的一个内部对象,只能在函数内部使用。
总的原则:this指的是,调用函数的那个对象。
函数的几种情况和对应的this值:
一. 全局的函数调用
此时this代表全局对象
二. 作为对象方法的调用
此时this指这个上级对象
三.作为构造函数调用
通过这个函数生成一个新对象(object)。this指这个新对象。
四.apply调用
apply()是函数对象的一个方法。对象的一个属性,属性值是函数,那个这个属性可以调用apply()方法启动。
它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。apply()的参数为空时,默认调用全局对象。
总的原则:this指的是,调用函数的那个对象。
函数的几种情况和对应的this值:
一. 全局的函数调用
此时this代表全局对象
function test(){ alert(this); return this; } test();//alert([object Window]) //return Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
二. 作为对象方法的调用
此时this指这个上级对象
function test(){ alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m(); // 1
三.作为构造函数调用
通过这个函数生成一个新对象(object)。this指这个新对象。
function test(){ this.x = 1; } var o = new test(); alert(o.x);//1 var o = {x:1}
四.apply调用
apply()是函数对象的一个方法。对象的一个属性,属性值是函数,那个这个属性可以调用apply()方法启动。
它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。apply()的参数为空时,默认调用全局对象。
function test(){ alert(this.x); } var o={}; o.x = 1; o.m = test; o.m(); //1 o.m.apply(); //undefined
相关文章推荐
- 关于前端开发学习的反思与规划
- 关于Cocos2d-X 学习中遇到的一些难以理解的东西 将来将会一一删除
- 关于抽象工厂的学习理解
- caffe学习笔记33-关于1*1卷积核理解
- 关于linux系统的日志文件的学习与理解
- 关于电脑启动流程,MBR,PBR的学学习和理解。
- 关于迁移学习的high level理解
- 关于线性基的学习与理解
- 关于前端的photoshop初探的学习笔记
- 关于正在学习的一个项目的理解(1)
- 前端,别闹 学习Javascript闭包(Closure)及几个经典面试题理解
- 由学习wc的extjs项目,想到的关于1学习一门编程语言 2extjs框架 3对所有框架的一个理解 4对事物真谛的理解
- [前端] nodejs dns模块学习理解
- 学习笔记第一天,关于div+css的理解
- 前端知识--学习理解JS
- c++学习之--关于堆栈理解
- 【前端学习笔记】2015-09-08~~~~ 关于切图的简单方法
- Java学习中关于I/O的理解(File类)1
- 关于linux里pg command 命令的简单理解——学习笔记
- JQuery选择器大全 前端面试送命题:面试题篇 对IOC和DI的通俗理解 c#中关于协变性和逆变性(又叫抗变)帮助理解