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 ...
随机推荐
- Application的多种值判断测试程序
Application.Contents.Remove("FriendLink") Response.Write("Application.Contents.Remove ...
- 源码篇:SDWebImage
攀登,一步一个脚印,方能知其乐 源码篇:SDWebImage 源码来源:https://github.com/rs/SDWebImage 版本: 3.7 SDWebImage是一个开源的第三方库,它提 ...
- ReactiveCocoa & FRP & MVVM
Functional Reactive Programming(以下简称FRP)是一种响应变化的编程范式.先来看一小段代码 a = 2 b = 2 c = a + b // c is 4 b = 3 ...
- Lucene add、updateDocument添加、更新与search查询(转)
package com.lucene; import java.io.IOException; import org.apache.lucene.analysis.standard.Stand ...
- POJ 2635 The Embarrassed Cryptographer(大数求余)
题意:给出一个大数,这个大数由两个素数相乘得到,让我们判断是否其中一个素数比L要小,如果两个都小,输出较小的那个. 分析:大数求余的方法:针对题目中的样例,143 11,我们可以这样算,1 % 11 ...
- WindowsAPI 之 CreatePipe、CreateProcess
MSDN介绍 CreatePipe A pipe is a section of shared memory that processes use for communication. The pro ...
- PHP开发利器zend studio常见问题解答
1.如何将zend studio 9的默认GBK编码设置为其它编码,例如UTF-8? 选择window菜单->Preferences->General->Workspace,在界面当 ...
- JavaScript返回上一页并自动刷新
返回并刷新 <script>alert("恭喜您,操作成功!"); window.location.href=document.referrer; </scrip ...
- 两种不同的重置样式方法(normalize.css)
重置样式非常多,凡是一个前端开发人员肯定有一个常用的重置CSS文件并知道如何使用它们.他们是盲目的在做还是知道为什么这么做呢?原因是不同的浏览器对一些元素有不同的默认样式,如果你不处理,在不同的浏览器 ...
- As Fast As Possible
As Fast As Possible On vacations n pupils decided to go on excursion and gather all together. They n ...