[Javascript] The "this" keyword

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.

时间: 2024-10-16 15:43:46

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

JavaScript Interview Questions: Event Delegation and This

David Posin helps you land that next programming position by understanding important JavaScript fundamentals. JavaScript is a fun, powerful, and important language with a low barrier of entry. People from all kinds of backgrounds and careers find the

javascript示例

如显示效果上图所示: 如图显示鼠标放在百度谷歌等字样上市动态显示其内容明细:代码如下:<head><title></title><script type="text/javascript">function initEvent() {var links = document.getElementsByTagName("a");//获取标签为a的内容for (var i =0; i < links.length;

JavaScript、SSH知识点整理

七.Javascript部分 1:什么是Javascript JavaScript是一种基于对象(Object)和事件驱动(Event Driven)并具有安全性能的脚本语言. 2:Java和Javascript的差别 1.基于对象和面向对象 Java是一种真正的面向对象的语言.即使是开发简单的程序,必须设计对象. JavaScript是种脚本语言,它能够用来制作与网络无关的,与用户交互作用的复杂软件. 它是一种基于对象(Object Based)和事件驱动(Event Driver)的编程语言

javascript fundamental concept

function: function本身是一个object,它可以被赋值给任何变量 immediate invoked function expression(IIFE):  function(){}() method vs function: 一个method是一个对象的一个函数属性(a method is a function that is a property of an object)例如: var console={ log:function(){} } console.log(“l

我希望自己尽早知道的 7 个 JavaScript 怪癖(转载oschina)

如果对你来说JavaScript还是一门全新的语言,或者你是在最近的开发中才刚刚对它有所了解,那么你可能会有些许挫败 感.任何编程语言都有它自己的怪癖(quirks)--然而,当你从那些强类型的服务器端语言转向JavaScript的时候 ,你会感到非常困惑.我就是这样!当我在几年前做全职JavaScript开发的时候,我多么希望关于这门语言的许多事情我能尽早地知道.我希望通过本文中分享的一些怪癖能让你免于遭受我所经历过的那些头疼的日子.本文并非一个详尽的列表,只是一些取样,目的是抛砖引玉,并且让

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

JavaScript中的new关键字可以实现实例化和继承的工作,但个人认为使用new关键字并非是最佳的实践,还可以有更友好一些的实现.本文将介绍使用new关键字有什么问题,然后介绍如何对与new相关联的一系列面向对象操作进行封装,以便提供更快捷的.更易让人理解的实现方式. 传统的实例化与继承 假设我们有两个类,Class:function Class() {}和SubClass:function SubClass(){},SubClass需要继承自Class.传统方法一般是按如下步骤来组织和实现

[ECSHOP二次开发]解决分类商品Ajax连续请求导致的数据重复

0x00: 首先声明一个全局变量. var control = true; 然后,在滑动处罚ajax请求的代码处,做一个判断. if (control) { $('.get_more').click(); }; 这个地方是获取数据的函数以及ajax请求的函数 get_data: function() { var ile; control=false;    //首先进来这个函数之后吧全局变量设置成false以防重复请求 lock = true; target.children(".more_lo

coffeescript 1.8.0 documents

CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way. The golden rule

掌握JS中的“this” (一)

译者注: 一般来说,function 翻译为函数, method 翻译为方法. 我们一般说, 某某对象的方法, 而不说 "某某对象的函数".原因是在面向对象中, 一个对象就是一个具体额实例,有自己的方法. 而函数,是和对象没关系的. 另外, scope(作用域) 和 context(上下文) 也是一个容易迷糊的地方.请参考: Javascript Context和Scope的一些学习总结 推荐阅读: 深入浅出ES6(1~10)系列 会用一门语言来写程序,并不代表就能正确地理解和使用该语