博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Javascript] The "this" keyword
阅读量:5049 次
发布时间:2019-06-12

本文共 5814 字,大约阅读时间需要 19 分钟。

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(); // Jimjim.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();  //undefinedwindow.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.

转载于:https://www.cnblogs.com/Answer1215/p/4696253.html

你可能感兴趣的文章
UIActionSheet 修改字体颜色
查看>>
Vue 框架-01- 入门篇 图文教程
查看>>
Spring注解之@Lazy注解,源码分析和总结
查看>>
多变量微积分笔记24——空间线积分
查看>>
Magento CE使用Redis的配置过程
查看>>
poi操作oracle数据库导出excel文件
查看>>
(转)Intent的基本使用方法总结
查看>>
Mac 下的Chrome 按什么快捷键调出页面调试工具
查看>>
Windows Phone开发(24):启动器与选择器之发送短信
查看>>
JS截取字符串常用方法
查看>>
Google非官方的Text To Speech和Speech Recognition的API
查看>>
stdext - A C++ STL Extensions Libary
查看>>
Django 内建 中间件组件
查看>>
bootstrap-Table服务端分页,获取到的数据怎么再页面的表格里显示
查看>>
进程间通信系列 之 socket套接字及其实例
查看>>
天气预报插件
查看>>
Unity 游戏框架搭建 (十三) 无需继承的单例的模板
查看>>
模块与包
查看>>
mysql忘记root密码
查看>>
apache服务器中设置目录不可访问
查看>>