The very first thing to understand when we're talking about this-keyword is really understand what's the purpose of the this-keyword is, or why we even have this-keyword in JavaScript.

What the this-keyword allows us to do, is it allows us to reuse functions with different contexts, or in other words it allows us to decide which objects should be focal when invoking a function or a methods. Imagine we had one function, and we had a bunch of objects that had similar properties, we want that function to work throughout all of our objects.

The first thing you need to ask yourself whenever you're trying to figure out what the this-keyword is, is this question. Where is this function invoked? We won't know what the this-keyword is in a function until that function is invoked.

There are four this keyword binding:

  1. Implicit Binding
  2. Explicit Binding
  3. New Binding
  4. Window Binding
  • Implicit Binding

Implicit binding says that when you call a function and when the function is invoked, look to the left of the dot, and that is what the this-keyword is going to reference.

var me = {
name: "Wan",
age: 26,
sayName: function(){
console.log(this.name);
}
} me.sayName();
var sayNameMixin = function(obj){
obj.sayName = function(){
console.log(this.name);
}
} var you = {
name: "Zhenitan",
age: 27
} sayNameMixin(me);
sayNameMixin(you); me.sayName(); //wan
you.sayName(); //Zhentian
var Person = function(name, age){

    return {
name: name,
age: age,
sayName: function(){
console.log(this.name);
},
mother: {
name: "Yun",
sayName: function(){
console.log(this.name);
}
}
}
} var jim = Person('Jim', 42);
jim.sayNmae(); // Jim
jim.mother.sayNmae(); //Yun

you're going to find that whenever you get in these situation of trying to figure out what the this-keyword is, the very first thing you should do is look at when the function was invoked, and look if there's anything to the left of the dot, because if there is, that's what this-keyword is referencing.


  • Explicit Binding

.call()

What if we were to take SayName out of this function? Instead of being a method on the object, now, it's just a function currently on the global scope. Now, what we want to do is we want to somehow call this function in the context of wan. What we can do is if we type the function name, every function has a .call property that allows us to do just that.

 var sayName = function(){
console.log(this.name);
} var wan = {
name: "Wan",
age: 27
}; sayName.call(wan);

let's go ahead and say if we wanted to pass a parameter, pass a few more arguments to SayName, what we can do is, let's say we had an array of languages.

 var sayName = function(lang1, lang2, lang3){
console.log("My name is "+ this.name + ', and I know' + lang1 + ', '+ lang2 + ', '+ lang3);
} var wan = {
name: "Wan",
age: 27
}; var languages = ['Javascript', 'Ruby', 'Python']; sayName.call(wan, languages[0], languages[1], languages[2]);

What we can do here in .call, the very first argument you pass is the context, and every argument after that is going to be passed to the function, just as a normal argument.

.apply()

It would be nicer if we could just pass in languages, and some feature in the language of JavaScript would be able to parse these out to us.

 var sayName = function(lang1, lang2, lang3){
console.log("My name is "+ this.name + ', and I know' + lang1 + ', '+ lang2 + ', '+ lang3);
} var wan = {
name: "Wan",
age: 27
}; var languages = ['Javascript', 'Ruby', 'Python']; sayName.apply(wan, languages);

.bind()

.bind is almost the exact same thing as .call, except there's one thing that's different. It returns a new function.

 var sayName = function(lang1, lang2, lang3){
console.log("My name is "+ this.name + ', and I know' + lang1 + ', '+ lang2 + ', '+ lang3);
} var wan = {
name: "Wan",
age: 27
}; var languages = ['Javascript', 'Ruby', 'Python']; var newFn = sayName.bind(wan, languages[0],languages[1],languages[2]);
newFn();

To reacp, .call, apply and bind allow us to specifically state what this keyword will be within any given function. .call and .apply behave the same way, they will immediatelyh invoke that funciton, but with .call, you pass in arguments one by one, and with .apply, you pass them in as an array. .bind is the exact same thing as .call, but execpt for immediately invoking the function, it's going to return you a brand new function that you can invoke later.


  • New Binding
var Animal = function(name, age){
// this = {};
this.name = name;
this.age = age;
}; var dog = new Animal('Zippy', 3);

When you use 'new' keyword, Javascript will auto create a 'this' keyword and assgin it as an object.


  • Window Binding
var greeting = function(){
console.log(this.message);
} greeting(); //undefined
window.message = "Hello";
greeting(); //"Hello"

In the console, we want to log out 'this.message', but we didn't use implict binding, so it shows undefined.

In javascript, if none of above three methods applyed, 'this' keyword will refer to the 'window' object, so if we assign

window.message = "Hello"

in greeting() will log out Hello.

To recap all our rules, we have implicit binding, which is you look to the left of the dot, at call time, explicit binding, which is telling a function what the context of the this keyword is going to be using call, apply, or bind.

The new binding is whenever you have a function invoked with the new keyword, the this keyword is bound to the new object being constructed. Then the Window binding where if none of these rules apply, then the this keyword is going to default to the Window object unless you're in strict mode. Then it's just going to be undefined.

[Javascript] The "this" keyword的更多相关文章

  1. javascript实例备忘

    一,javascript动态显示: 如显示效果上图所示: 如图显示鼠标放在百度谷歌等字样上市动态显示其内容明细:代码如下:<head><title></title> ...

  2. Javascript的实例化与继承:请停止使用new关键字

    本文同时也发表在我另一篇独立博客 <Javascript的实例化与继承:请停止使用new关键字>(管理员请注意!这两个都是我自己的原创博客!不要踢出首页!不是转载!已经误会三次了!) 标题 ...

  3. 我希望我知道的七个JavaScript技巧

    如果你是一个JavaScript新手或仅仅最近才在你的开发工作中接触它,你可能感到沮丧.所有的语言都有自己的怪癖(quirks)——但从基于强类型的服务器端语言转移过来的开发人员可能会感到困惑.我就曾 ...

  4. Javascript + Dom知识点总结

    Javascript + Dom知识点总结 1.用Javascript声明数组和字典的方式 // 数组声明 var arr = new Array(); arr["0"] = &q ...

  5. JavaScript Interview Questions: Event Delegation and This

    David Posin helps you land that next programming position by understanding important JavaScript fund ...

  6. javascript fundamental concept

    http://hzjavaeyer.group.iteye.com/group/wiki?category_id=283 上面这个url非常适合javascript初学者阅读,感谢原作者的分享 什么是 ...

  7. [转]JavaScript的实例化与继承:请停止使用new关键字

    JavaScript中的new关键字可以实现实例化和继承的工作,但个人认为使用new关键字并非是最佳的实践,还可以有更友好一些的实现.本文将介绍使用new关键字有什么问题,然后介绍如何对与new相关联 ...

  8. Understand JavaScript’s “this” With Clarity, and Master It

    The this keyword in JavaScript confuses new and seasoned JavaScript developers alike. This article a ...

  9. [ javascript ] getElementsByClassName与className和getAttribute!

    对于javascript中的getElementsByClassName 在IE 6/7/8 不支持问题. 那么须要模拟出getElementsByClassName  须要採用className属性 ...

随机推荐

  1. 反射生成SQL语句

    public static int Reg(Model ml) { bool b = true; Visit vt = new Visit(); StringBuilder builder = new ...

  2. APUE1

    [APUE]进程控制(上)   一.进程标识 进程ID 0是调度进程,常常被称为交换进程(swapper).该进程并不执行任何磁盘上的程序--它是内核的一部分,因此也被称为系统进程.进程ID 1是in ...

  3. SQL Server并行死锁案例解析

    并行执行作为提升查询响应时间,提高用户体验的一种有效手段被大家所熟知,感兴趣的朋友可以看我以前的博客SQL Server优化技巧之SQL Server中的"MapReduce", ...

  4. Android编译错误, Ignoring InnerClasses attribute for an anonymous inner class

    今天在做android项目时,加入第三方包,一编译就报错.错误如下:[2012-01-13 14:51:25 - xxx] Dx warning: Ignoring InnerClasses attr ...

  5. Docker学习笔记整理

    Docker接触有一段时间了,但是对于Docker的使用可以说是一点不会.现在要在Docker上部署基于Angular开发的页面.只能一点点积累查找的资料,顺手整理一下,方便后面的回顾. 其中用到的资 ...

  6. MVC4+WebApi+Redis Session共享练习(下)

    上一篇文章我们主要讲解了一些webApi和redis缓存操作,这篇文章我们主要说一些MVC相关的知识(过滤器和错误处理),及采用ajax调用webApi服务. 本篇例子采用的开发环境为:VS2010( ...

  7. UTL_FILE建文件失败“ORA-29280: 目录路径无效”错误

    存储过程写文件需要配置可写的目录,具体是utl_file_dir这个参数,把UTL_FILE输出的目录写到这个参数,如果不限制,可以令utl_file_dir=*   查看:   SQL> sh ...

  8. 你在用什么思想编码:事务脚本 OR 面向对象?

    最近在公司内部做技术交流的时候,说起技能提升的问题,调研大家想要培训什么,结果大出我意料,很多人想要培训:面向对象编码.于是我抛出一个问题:你觉得我们现在的代码是面向对象的吗?有人回答:是,有人回答否 ...

  9. [stm32] GPIO及最小框架

    1.GPIO硬件结构图: 2.GPIO程序结构: 3.框架介绍: 这里的ASM是固定启动文件夹,startup_stm32f10x_hd.s表示当前stm32类型为高容量设备,当然还有md.s等. C ...

  10. JsRender实用教程(tag else使用、循环嵌套访问父级数据)

    前言 JsRender是一款基于jQuery的JavaScript模版引擎,它具有如下特点: ·  简单直观 ·  功能强大 ·  可扩展的 ·  快如闪电 这些特性看起来很厉害,但几乎每个模版引擎, ...