`

javascript之function的this

阅读更多
javascript之function的this

一、this 的定义 与 函数的调用

在 javascript 中, function 中的 this 指代的是: 调用 function 执行时的上下文。
也就是说,调用哪个对象的 function,this就指代哪个对象。默认是 window 对象。

1. this 可以指代一个普通对象
var Bucky = {
    pringtFirstName: function(){
        console.log("My name is Bucky.");
        console.log( this === Bucky );   // true
    }
}
Bucky.pringtFirstName();


2. this 可以指代 默认的 window 对象
function doSomethingWorthless(){
    console.log("I am worthless.");
    console.log( this === window );      // true
}
doSomethingWorthless();                  // window.doSomethingWorthless(); 



3. this 可以指代 function 对象的 prototype 对象

var foo = function(){};
foo.prototype.sayHello = function(){
    this.name = "Hello,World!"; 
}
foo.prototype.sayHello();

console.log(foo.prototype.name);     // "Hello,World!"



4. this 可以指代 function 对象的 一个实例

foo = function(){} 
foo.prototype.sayHello = function(){
    this.name = "Hello World !";
} 

var f = new foo();
f.sayHello();

console.log(f.name);     // "Hello World !";



可以看出:
     1) 调用哪个对象的 function , this 就指代哪个对象。
     2) 所调用的对象,即:function运行时的上下文。
     3) this 与 怎样调用 function 有关。



二、函数运行时,this 的引用

1. this 可以在 function 的 prototype 对象中被引用

foo = function(){   
    this.name = "Foo function.";   
}   

foo.prototype.sayHello = function(){  
    console.log( this.name );     //"Foo function."   
}   

var f = new foo();   
f.sayHello();                     // sayHello() 运行的上下文环境是 f 对象






三、function 中与 this 相关的两个函数: apply(), call()

前面说了,既然 this 是与调用 function 的对象有关。
那么,当调用对象的 function 时,是否可以指定一个运行时的上下文 this 对象?



1、理解 function 的 apply() 方法。

The apply() method calls a function with a given this value and arguments provided as an array.

   apply 什么呢? 把当前的对象(只要类型是 object 即可) apply 给 function,作为该 function 的 this 对象。
   apply 方法针对的是将要执行的 function 的 this。 它可以在调用函数时,指定一个它的 this 对象。
   即:在已经有预设定值的对象上,继续进行this的创建。

1) this 指向执行函数的对象 - 将 function 作为参数

foo = function(){   
    this.name = "Foo function.";   
}   

foo.prototype.sayHello = function(){  
    var me = this;             // this 在这里是 window 对象。

    console.log(me.name);      // null
    console.log(this.f.name);  //"Foo function."
}   

var f = new foo();   
setTimeout(f.sayHello, 1000);   // 运行的是 window.setTimeout()



2) this 指向执行函数的对象 - 直接执行函数

foo = function(){   
    this.name = "Foo function.";   
}   

foo.prototype.sayHello = function(){  
    var me = this;             // this 在这里是 f 对象。

    console.log(me.name);      // "Foo function."
    console.log(this.f.name);  // 报错:f 未定义
}   

var f = new foo();   
f.sayHello();                  // 运行的是 f 



3) this 指向执行函数的对象 - 指定一个 this 执行

foo = function(){   
    this.name = "Foo function.";   
}   

foo.prototype.sayHello = function(){  
    var me = this;             // this 在这里是 window 对象。

    console.log(me.name);      // null
    console.log(this.f.name);  //"Foo function."
}   

var f = new foo();   
f.sayHello.apply(this, window); // 指定 this 为 window 对象





apply() 方法有两个目地:

1. 指定函数执行时的 this 对象;
2. 运行函数。
  (这个目地似乎没有通过从 apply 的方法名称上体现出来,
    或许应该叫: apply_and_run 更能体现出这个方法的作用 )


———————————————————————————————————————————————————————————————————————————


扩展阅读:function 中与 this 相关的另一个函数: bind()


The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

对比 apply() / call():
apply()/ call() 用来调用(执行)函数,而 bind() 用来创建函数。

Syntax
fun.bind(thisArg[, arg1[, arg2[, ...]]])



Parameters

thisArg
The value to be passed as the this parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the new operator.

arg1, arg2, ...
Arguments to prepend to arguments provided to the bound function when invoking the target function.




this.x = 9; 
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var retrieveX = module.getX;
retrieveX();  // returns 9 - The function gets invoked at the global scope


// Create a new function with 'this' bound to module
// New programmers might confuse the
// global var x with module's property x
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81





参考:
Preserving a reference to “this” in JavaScript prototype functions
http://stackoverflow.com/questions/2025789/preserving-a-reference-to-this-in-javascript-prototype-functions





—————————————

javascript 函数基础系列文章

1、JavaScript之变量的作用域
2、javascript之变量类型与变量声明及函数变量的运行机制
3、javaScript之function定义
4、javascript之function的prototype对象
5、javascript之function的(closure)闭包特性
6、javascript之function的this   
7、javascript之function的apply(), call()



___________


javascript 面向对象编程系列文章:

    1、javaScript之面向对象编程
    2、javascript之面向对象编程之属性继承
    3、javascript之面向对象编程之原型继承 
   

-





-
引用请标明
原文出处: http://lixh1986.iteye.com/blog/1960343







-
分享到:
评论

相关推荐

    javascript 中 this 的用法.docx

    JavaScript 中的 this 关键字是一个非常重要的概念,它经常会使开发者感到困 惑。通常来说,this 的值是在函数被调用时确定的,其值取决于函数被调用的方 式。本文将介绍 JavaScript 中 this 的用法,从而帮助开发者...

    JavaScript应用实例-1箭头函数和function的this对比.js

    JavaScript应用实例-1箭头函数和function的this对比.js

    深入理解JavaScript系列

    深入理解JavaScript系列(6):S.O.L.I.D五大原则之单一职责SRP 深入理解JavaScript系列(7):S.O.L.I.D五大原则之开闭原则OCP 深入理解JavaScript系列(8):S.O.L.I.D五大原则之里氏替换原则LSP 深入理解...

    深入理解JavaScript系列(.chm)

    深入理解JavaScript系列(13):This Yes this 深入理解JavaScript系列(14):作用域链 Scope Chain 深入理解JavaScript系列(15):函数(Functions) 深入理解JavaScript系列(16):闭包(Closures) 深入...

    浅谈JavaScript 中的this

    JavaScript 中的this 1.this是什么? ​ 函数调用的时候会创建上下文,this 是组成上下文的一部分。因此每次函数被调用都会产生新的this,既this的值就是调用当前函数的对象。 2.作为普通函数在全局作用域中被使用 ...

    Professional JavaScript for Web Developers英文版

    This book provides a developer-level introduction along with more advanced and useful features of JavaScript. Coverage includes: JavaScript use with HTML to create dynamic webpages, language concepts ...

    c#与JavaScript交互

    function test() { alert("oec2003"); return false; } c#代码: protected void Button1_Click(object sender, EventArgs e) { ClientScript.RegisterStartupScript(this.GetType(), "clear", ...

    老生常谈Javascript中的原型和this指针

    1、Javascript中的原型: 原型prototype是Javascript中特有的一个概念。通过原型,Javascript可以实现继承机制。 ... this.getName = function(){ return this.name; } } function Artist(type){

    【JavaScript源代码】NodeJS和浏览器中this关键字的不同之处.docx

    NodeJS和浏览器中this关键字的不同之处  学习过JavaScript的人肯定清楚 处在不同环境下this的指向问题。那么看下面的代码 var type = 1 function toWhere(){ this.type = 2; } toWhere(); console.log(type)...

    Programming JavaScript Applications

    With this digital Early Release edition of Programming JavaScript Applications, you get the entire book bundle in its earliest form—the author's raw and unedited content—so you can take advantage of...

    JavaScript this 深入理解

    直到昨天翻了一下《JavaScript王者归来》这本书才算对this有一个深刻的理解。 大至归结一下: 1. 函数调用者与所有者 JavaScript 中函数(function) 存在调用者 与 所有者这两个概念,调用者是指调用函数的对象,通常...

    JavaScript Patterns

    * Discover different ways to define a function in JavaScript * Create objects that go beyond the basic patterns of using object literals and constructor functions * Learn the options available for ...

    深入理解Javascript中this的作用域

    大家在使用Javascript的时候经常被this这个家伙搞得晕头转向的。对大多数有OOP开发经验的开发人员来说this是当前作用域中引用普通元素的标识符,但是在Javascript中它却显得古灵精怪的,因为它不是固定不变的,而是...

    JavaScript Functional Programming for JavaScript Developers (PDF, EPUB, MOBI)

    This course will begin with providing insights and practical tips on advanced JavaScript features to build highly scalable web and mobile system and move on to some design patterns with JavaScript....

    JavaScript函数的调用以及参数传递

    一般而言,在Javascript中,this指向函数执行时的当前对象。 Note 注意 this 是保留关键字,你不能修改 this 的值。 调用 JavaScript 函数 函数中的代码在函数被调用后执行。 作为一个函数调用 实例 function ...

    javascript之this详解

    this关键字 每个函数都有一个关键字叫this,在不同的情况下,this代表的内容也是不同的 1. 普通函数中的this代表window对象 function fn(){ console.log(this); } fn(); // window 2.定时器中的this代表window对象...

    javascript面向对象编程指南 2nd

    What you will learn from this book The basics of object-oriented programming, and how to apply it in the JavaScript environment How to set up and use your training environment (Firebug) In depth ...

    【JavaScript源代码】Javascript中函数分类&this指向的实例详解.docx

    Javascript中函数分类&this指向的实例详解  通过实例来说明吧 <script> //method1 function fn() { console.log('fn created '); } //method2 var fn2 = function () { console.log('fn2 created'); } //...

    JavaScript使用function定义对象并调用的方法

    本文实例讲述了JavaScript使用function定义对象并调用的方法。分享给大家供大家参考。具体分析如下: JS中你可以通过函数的方式定义对象,下面的JS代码定义了一个movie的函数对象,然后通过new的方法声明对象,调用...

Global site tag (gtag.js) - Google Analytics