javascript 中的this
he scope of all functions is window
.
(The reason why is you are invoking f
as a function(类,全局的类)
and not a method
. When invoked as a function this
is set to window
during the execution of the target)
To circumvent that, you can do this:
A.prototype.go = function() {
var self = this;
console.log(self); //A { go=function()}
var f = function() {
console.log(self); //A { go=function()}
}; f();
}
this
would only not refer to the window when it is in the method of a class and not just a regular function. –
看一段有意思的代码,猜测一下,弹出的 this 变量会是什么?
function Menu(elem) {
alert(this);
function privateMethod() {
alert(this) // window, not menu!
} // ... call private method
privateMethod()
} new Menu(document.createElement('div'))
Because function f()
is not called without any object reference. Try,
f.apply(this);
function Menu(elem) {
alert(this);
function privateMethod() {
alert(this) // window, not menu!
} // ... call private method
privateMethod.apply(this)
} new Menu(document.createElement('div'))
——---------------------------------------------------------------------------------------------------------------------------
参考 stack-overflow:
http://javascript.info/tutorial/binding
JavaScript has a different concept of what the special name this
refers to than most other programming languages do. There are exactly five different ways in which the value of this
can be bound in the language.
The Global Scope
this;
When using this
in global scope, it will simply refer to the global object.
Calling a Function
foo();
Here, this
will again refer to the global object.
ES5 Note: In strict mode, the global case no longer exists.
this
will instead have the value ofundefined
in that case.
Calling a Method
test.foo();
In this example, this
will refer to test
.
Calling a Constructor
new foo();
A function call that is preceded by the new
keyword acts as a constructor. Inside the function, this
will refer to a newly created Object
.
Explicit Setting of this
function foo(a, b, c) {}
var bar = {};
foo.apply(bar, [1, 2, 3]); // array will expand to the below
foo.call(bar, 1, 2, 3); // results in a = 1, b = 2, c = 3
When using the call
or apply
methods of Function.prototype
, the value of this
inside the called function gets explicitly set to the first argument of the corresponding function call.
As a result, in the above example the method case does not apply, and this
inside of foo
will be set to bar
.
Note:
this
cannot be used to refer to the object inside of anObject
literal. Sovar obj = {me: this}
will not result inme
referring toobj
, sincethis
only gets bound by one of the five listed cases.
Common Pitfalls
While most of these cases make sense, the first one is to be considered another mis-design of the language because it never has any practical use.
Foo.method = function() {
function test() {
// this is set to the global object
}
test();
}
A common misconception is that this
inside of test
refers to Foo
; while in fact, it does not.
In order to gain access to Foo
from within test
, it is necessary to create a local variable inside of method
which refers to Foo
.
Foo.method = function() {
var that = this;
function test() {
// Use that instead of this here
}
test();
}
that
is just a normal variable name, but it is commonly used for the reference to an outer this
. In combination with closures, it can also be used to pass this
values around.
Assigning Methods
Another thing that does not work in JavaScript is function aliasing, which is assigning a method to a variable.
var test = someObject.methodTest;
test();
Due to the first case, test
now acts like a plain function call; therefore, this
inside it will no longer refer to someObject
.
While the late binding of this
might seem like a bad idea at first, in fact, it is what makes prototypal inheritance work.
function Foo() {}
Foo.prototype.method = function() {};
function Bar() {}
Bar.prototype = Foo.prototype;
new Bar().method();
When method
gets called on a instance of Bar
, this
will now refer to that very instance.
Disclaimer: Shamelessy stolen from my own resources at http://bonsaiden.github.com/JavaScript-Garden/#function.this
javascript 中的this的更多相关文章
- javascript中的Array对象 —— 数组的合并、转换、迭代、排序、堆栈
Array 是javascript中经常用到的数据类型.javascript 的数组其他语言中数组的最大的区别是其每个数组项都可以保存任何类型的数据.本文主要讨论javascript中数组的声明.转换 ...
- javascript中的this与函数讲解
前言 javascript中没有块级作用域(es6以前),javascript中作用域分为函数作用域和全局作用域.并且,大家可以认为全局作用域其实就是Window函数的函数作用域,我们编写的js代码, ...
- JavaScript 中的数据类型
Javascript中的数据类型有以下几种情况: 基本类型:string,number,boolean 特殊类型:undefined,null 引用类型:Object,Function,Date,Ar ...
- javascript中的操作符详解1
好久没有写点什么了,根据博主的技术,仍然写一点javascript新手入门文章,接下来我们一起来探讨javascript的操作符. 一.前言 javascript中有许多操作符,但是许多初学者并不理解 ...
- 掌握javascript中的最基础数据结构-----数组
这是一篇<数据结构与算法javascript描述>的读书笔记.主要梳理了关于数组的知识.部分内容及源码来自原作. 书中第一章介绍了如何配置javascript运行环境:javascript ...
- javascript中变量提升的理解
网上找了两个经典的例子 var foo = 1; function bar() { if (!foo) { var foo = 10; } alert(foo); } bar(); // 10 var ...
- 前端开发:面向对象与javascript中的面向对象实现(二)构造函数与原型
前端开发:面向对象与javascript中的面向对象实现(二)构造函数与原型 前言(题外话): 有人说拖延症是一个绝症,哎呀治不好了.先不说这是一个每个人都多多少少会有的,也不管它究竟对生活有多么大的 ...
- 简单分析JavaScript中的面向对象
初学JavaScript的时候有人会认为JavaScript不是一门面向对象的语言,因为JS是没有类的概念的,但是这并不代表JavaScript没有对象的存在,而且JavaScript也提供了其它的方 ...
- Javascript中的valueOf与toString
基本上,javascript中所有数据类型都拥有valueOf和toString这两个方法,null除外.它们俩解决javascript值运算与显示的问题,本文将详细介绍,有需要的朋友可以参考下. t ...
- 关于javascript中的this关键字
this是非常强大的一个关键字,但是如果你不了解它,可能很难正确的使用它. 下面我解释一下如果在事件处理中使用this. 首先我们讨论一下下面这个函数中的this关联到什么. function doS ...
随机推荐
- jquery 高亮
<ul> <li id="0">冬瓜很好吃</li> <li id="1">西瓜不好吃</li> & ...
- Phonegap解决错误:Error initializing Cordova:Class not found
Phonegap 解决错误: Alert [ERROR]Error initializing Cordova:Class not found 发现bug后找原因 网上说是 因为找不到 ...
- asp:Property解释与例子
=======================================================================Property Get 语句在 Class 块中,声明构 ...
- Android抽屉(SlidingDrawer --类似android通知栏下拉效果)
Android抽屉(SlidingDrawer)的实现发 - 红黑联盟http://www.2cto.com/kf/201301/182507.html 可动态布局的Android抽屉之基础http: ...
- C语言客户端服务器代码
/* sockclnt.c*/ #include <stdio.h>#include <string.h>#include <stdlib.h>#include & ...
- 转:Loadrunner报错“Too many local variablesAction.c”解决方法
问题描述,在Action.c里定义数组时如果数组长度过长,如char a[1024*1024]运行时即会报错: 问题原因及解决方法如下: 1. VuGen对于局部变量可以分配的最大内存为64K,如果想 ...
- 批量文件重命名工具-极力推荐 advanced renamer
http://www.advancedrenamer.com/ 功能太强大了,自己慢慢探索吧.
- 设置自己Eclipse代码风格(内部)
http://www.cnblogs.com/farseer810/p/4391318.html 经过这几次的代码提交,发现很多人的代码风格不够规范.个人认为很有必要强制性规定一下代码的规范. 整体来 ...
- AJAX(XMLHttpRequest)进行跨域请求方法详解(一)
注意:以下代码请在Firefox 3.5.Chrome 3.0.Safari 4之后的版本中进行测试.IE8的实现方法与其他浏览不同. 跨域请求,顾名思义,就是一个站点中的资源去访问另外一个不同域名站 ...
- 使用nodejs的net模块创建TCP服务器
使用nodejs的net模块创建TCP服务器 laiqun@msn.cn Contents 1. 代码实现 2. 使用telnet连接服务器测试 3. 创建一个TCP的client 1. 代码实现 ; ...