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://stackoverflow.com/questions/9674252/javascript-why-this-inside-the-private-function-refers-to-the-global-scope

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 of undefined 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, thiswill 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 an Object literal. So var obj = {me: this} will not result in me referring to obj, since this 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 Barthis will now refer to that very instance.

Disclaimer: Shamelessy stolen from my own resources at http://bonsaiden.github.com/JavaScript-Garden/#function.this

时间: 2024-07-30 10:19:18

javascript 中的this的相关文章

实现一个函数clone,使JavaScript中的5种主要的数据类型(包括Number、String、Object、Array、Boolean)进行值复制

实现一个函数clone,可以对JavaScript中的5种主要的数据类型(包括Number.String.Object.Array.Boolean)进行值复制. 1 /** 对象克隆 2 * 支持基本数据类型及对象 3 * 递归方法 */ 4 function clone(obj) { 5 var o; 6 switch (typeof obj) { 7 case "undefined": 8 break; 9 case "string": o = obj + &q

javascript中的原始值和复杂值

前面的话 javascript的数据类型可以分为两种:原始类型(基本类型或者简单类型)和引用类型. 原始类型:Undefined,Null,Boolean,Number,String五种: 引用类型:Object,Array,Function: 与此相对应的,它们的值分别被称为原始值和复杂值. 特性 原始值 原始值是表示javascript中可用的数据或信息的最底层的形式或者最简单的形式.原始类型的值被称为原始值,因为它们的值是不可被细化的.也就是说,数字是数字,字符串是字符串,布尔值是true

【JS】JavaScript中的执行环境与作用域

JavaScript中的执行环境定义了变量或函数有权访问的数据(每个函数都有自己的执行环境),全局执行环境是最外围的执行环境,在浏览器中,全局执行环境就是window对象,所以所有的全局变量和函数都是作为window对象的属性和方法创建的.当某一个执行环境中所有代码执行完成后,该环境就被销毁,保存在其中的变量和函数也将被销毁,全局执行环境在关闭网页或浏览器时才被销毁. 当代码在一个环境中执行时,会创建变量对象的一个作用域链(保证对执行环境有权访问的变量和函数的有序访问),如果环境是函数,将其活动

JavaScript中的构造函数

function Accom(){};    //创建一个构造函数 //创建两个对象 var house=new Accom(); var apartment=new Accom(); 通过构造函数创建的对象有一个属性constructor,这个属性指向创建该对象时所用的Javascript构造函数. house.constructor===Accom;  或者   house instanceof Accom;     //true JavaScript中的每个构造函数都有一个prototyp

【转】十个JavaScript中易犯的小错误,你中了几枪?

在今天,JavaScript已经成为了网页编辑的核心.尤其是过去的几年,互联网见证了在SPA开发.图形处理.交互等方面大量JS库的出现. 如果初次打交道,很多人会觉得js很简单.确实,对于很多有经验的工程师,或者甚至是初学者而言,实现基本的js功能几乎毫无障碍.但是JS的真实功能却比很多人想象的要更加多样.复杂.JavaScript的许多细节规定会让你的网页出现很多意想不到的bug,搞懂这些bug,对于成为一位有经验的JS开发者很重要. 常见错误一:对于this关键词的不正确引用 我曾经听一位喜

JavaScript中Function的拓展

Function 是什么东西,就是JavaScript中的顶级类,系统级别的类.我们平时写的函数方法例如下. function Animal() { } Animal就是Function的实例,但是在我们的逻辑中 Animal是类,是自定义类. Function是类,Animal是类也是实例,Animal是Function的实例,Animal是自定义类.这点大家一定要搞清楚. 我们在顶级类上定义一个method的方法,用于进行键值对的方式进行方法链式的设定, Function.prototype

浅谈JavaScript中继承的实现

  谈到js中的面向对象编程,都有一个共同点,选择原型属性还是构造函数,两者各有利弊,而就片面的从js的对象创建以及继承的实现两个方面来说,官方所推荐的是两个相结合,各尽其责,各取其长,在前面的例子中,我已就在JavaScript中对象创建的方法做了一些总结,下面就其继承来道说一二:   1:原型链继承: 每一个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针,而实例都包含一个指向原型对象内部的指针(默认的原型,所有默认类型都继承了Object,而这个继承也是用过原型链实现) fu

理清javascript中prototype、__proto__、Object、Function的关系,更好地理解原型继承

本文参考了http://www.blogjava.net/heavensay/archive/2013/10/20/405440.html这篇文章,对其内容作了个简单总结,形成了几条简单的结论,让读者更容易记住prototype.__proto__.Object.Function之间的关系. 结论1:Object.prototype只是一个普通对象,它是js原型链的最顶端. (typeof Object.prototype) === object;//true Object.prototype.

javascript中的立即执行函数(function(){…})()

javascript中的立即执行函数(function(){…})() 深入理解javascript中的立即执行函数,立即执行函数也叫立即调用函数,通常它的写法是用(function(){…})()包住业务代码,使用jquery时比较常见. ( function(){…} )()和( function (){…} () )是两种javascript立即执行函数的常见写法,最初我以为是一个括号包裹匿名函数,再在后面加个括号调用函数,最后达到函数定义后立即执行的目的,后来发现加括号的原因并非如此.要

javascript中的栈、队列。

                       javascript中的栈.队列 栈方法     栈是一种LIFO(后进先出)的数据结构,在js中实现只需用到2个函数 push()  接受参数并将其放置数组尾,并返回修改后的数组长度. pop()  移除数组尾的最后一项,并返回移除项的值. 事例: var colors = new Array();var count = colors.push("red","green"); count = colors.push(&