Home > Web Front-end > JS Tutorial > body text

this object in Javascript

不言
Release: 2018-07-07 11:06:57
Original
1164 people have browsed it

This article mainly introduces the this object in Javascript, which has certain reference value. Now I share it with you. Friends in need can refer to it.

Regarding the use of this, we most often encounter The main ones are in global functions, in object methods, during call and apply, in closures, in arrow functions and in classes;

We know that this object is bound based on the execution environment of the function at runtime. Definitely, the value of this is not determined before the function is called, so this will refer to different objects during code execution. Which object instance calls the function where this is located, then this represents which object instance.

1. Global function

In the global function, this is equal to window;

var name = "Tina";function sayName() {
    alert(this.name);
}
person();//Tina
Copy after login

Here, since the function person() is executed in the global environment, and person() is also called by the window object in the global scope; therefore, this at this time points to the window object. When this function is assigned to object o and o.sayName() is called, this refers to object o, so the evaluation of this.name becomes the evaluation of o.name.

 name = "Tina"
Copy after login

2. Object methods

##When a function is called as a method of an object, this is equal to that object;

var name="Tina";var obj={
      name="Tony",
      getName: function() {
            alert(this.name);
      }
};
obj.getName();//"Tony"
Copy after login

3.call() and apply( ) and bind()

We know that the uses of call(ctx, parm1,parm2,parm3...) and apply(ctx,[parms]) are Calling a function in a specific scope is actually equivalent to setting the value of this object in the function body;

function sum(num1, num2)  {      return num1+num2;
}function callSum1(num1, num2) {      return sum.apply(this, [num1, num2]);
}function callSum2(num1,num2) {      return sum.call(this, num1, num2);
}
alert(callSum1(10, 10)); //20alert(callSum2(10, 10));//20
Copy after login

In the above example, callSum1() and callSum2( ) when executing function sum(), this is passed in as the this value (because it is called in the global scope, so the window object is passed in); in fact, the most powerful thing about call and apply is that it can expand the function The scope to run in; look at the following example:

window.color="red";var o={ color: "blue"};function sayColor() {
      alert(this.color);
}
sayColor();//"red"sayColor.call(this);//"red"sayColor.call(window);//"red"sayColor.call(o);//"blue"
Copy after login

The bind() method will create an instance of the function, and its this value will be bound to the value passed to the bind() function. For example:

window.color="red";var o={ color: "blue" };function sayColor() {
    alert(this.color);
}var objsayColor = sayColor.bind(o);
objsayColor();//"blue"
Copy after login

Another usage scenario is function binding. Function binding creates a function that can be called with specified parameters in a specific this environment. A function, this technique is often used with callback functions and event handlers to preserve the code execution environment while passing the function as a variable.

var handler = {
      message: "Event handled",
      handleClick : function(event) {
            alert(this.message);
      }
};var btn = document.getElementById("my_btn");
btn.addEventListener("click", handler.handleClick, false);
Copy after login

When the button is pressed, the function is called and a warning box is displayed. Although it seems that the warning box should display Event handled, it actually displays is undefined. The reason is that the execution environment of handler.handleClick() is not saved, so the this object finally points to the DOM button instead of the handler (in IE8, this points to the window). One way to fix this problem is to use a closure.

var handler = {
      message: "Event handled",
      handleClick : function(event) {
            alert(this.message);
      }
};var btn = document.getElementById("my_btn");
btn.addEventListener("click", function(event){
      handler.handleClick(event);
}, false);
Copy after login

This solution uses a closure within the onclick event handler to directly call handler.handleClick(). Of course, this is specific to this code. s solution. We know that creating multiple closures can make your code difficult to understand and debug. Therefore, many JS libraries implement a function that can bind a function to a specified environment. This function is generally called bind(); ECMAScript 5 defines a native bind() method for all functions, and its use is as follows:

var handler = {
      message: "Event handled",
      handleClick : function(event) {
            alert(this.message+":"+event.type);
      }
};var btn = document.getElementById("my_btn");
btn.addEventListenr("click", handler.handleClick.bind(handler), false);
Copy after login

A simple bind() function accepts one argument and an environment, and returns a function that calls the given function in the given environment, with all arguments Pass it on intact. The syntax is as follows:

function bind(fn, context) {      
return function() {            
return fn.apply(context, arguments);
      };
}
Copy after login

This function creates a closure in bind(). The closure uses apply to call the incoming function and passes context to apply. The object is an array of arguments objects. The arguments objects here are for internal functions (anonymous functions), not parameters for bind(). When the returned function is called, it executes the passed function in the given environment and gives all arguments.

The native bind() method is similar to the previously customized bind() method, both of which require passing in the object as this value. They are mainly used in event handlers and setTimeout() and setInterval(). Binding often plays the same role as the arrow function in binding this in react event processing.

4. Closure

Sometimes, due to the different ways of writing closures, using this object in closures may cause some problems;

var name = "The window";var object = {
      name: "My Object",
      getNameFunc: function() {            
      return function() {                  
      return this.name;
            };
      }
};
alert(object.getNameFunc()());//"The window"
Copy after login

由于getNameFunc()返回一个函数,因此调用object.getNameFunc()()就会立即调用它返回的函数,结果就是返回一个字符串"The window",即全局变量的值,此时匿名函数没有取得其包含作用域(外部作用域)的this对象。原因在于内部函数在搜索两个特殊变量this和arguments时,只会搜索到其活动对象为止,因此永远不可能直接访问外部函数中的这两个变量。这时,只需把把外部作用域中的this对象保存在一个闭包能够访问到的变量里,就可以让闭包访问该对象了。

var name = "The window";var object = {
      name: "My Object",
      getNameFunc: function() {            
      var that = this;            
      return function() {                  
      return that.name;
            };
      }
};
alert(object.getNameFunc()());//"My Object"
Copy after login

//节流function throttle(fn, delay) {      
var previous = Data.now();      
return function() {             
var ctx = this;             
var args = arguments;             
var now = Data.now();             
var diff = now-previous-delay;              
if(diff>=0) {
                    previous = now;
                    setTimeout(function() {
                         fn.apply(ctx, args);
                    }, delay);
              }
       };
}
Copy after login

5. 箭头函数

我们知道,箭头函数有几个需要注意的点:

(1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象;

(2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误;

(3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用rest参数代替;

(4)不可以使用yield命令,因此箭头函数不能用作Generator函数;

这里我们只谈论第一点;this对象的指向是可变的,但在箭头函数中,它是固定的;

function foo() {
      setTimeout(() => {
          console.log('id: ', this.id);
      }, 100);
}var id=21;
foo.call({id: 31});//id: 31
Copy after login

上述代码中,setTimeout是一个箭头函数,这个箭头函数的定义生效是在foo函数生成时,而它真正加入到执行栈后还要等到100毫秒后才会执行,如果是普通函数,此时的this应该指向全局对象window,这时应该输出21。但是,箭头函数导致this总是指向函数定义生效时所在的对象(本例是{id:31})所以输出的是id: 31;

箭头函数可以让setTimeout里面的this,绑定定义时所在的作用域,而不是指向运行时所在的作用域。下面是另一个例子:

function Timer() {      this.s1 = 0;      this.s2 = 0;
      setInterval(() => this.s1++, 1000);
      setInterval(function() {            this.s2++;
      }, 1000);
}var timer = new Timer();
setTimeout(() => console.log('s1: ', timer.s1), 3100);//s1: 3setTimeout(() => console.log('s2: ', timer.s2), 3100);//s2: 0
Copy after login

上面代码中,Timer函数内部设置了两个定时器,分别使用了箭头函数和普通函数。前者的this绑定定义时所在的作用域(Timer函数),后者的this指向运行时所在的作用域(即全局对象)。所以,3100毫秒后,timer.s1被更新了3次,timer.s2一次都没更新。

箭头函数可以让this指向固定化,这种特性很有利于封装回调函数。下面代码将DOM事件的回调函数封装在一个对象里面。

var handler = {
      id: '123456',
      init: function() {
            document.addEventListener('click',
                event => this.doSomething(event.type), false);
      },
      doSomething: funcition(type) {
            console.log('Handling ' + type + ' for ' + this.id);
      }
};
Copy after login

上面代码的init方法中,使用了箭头函数,这导致这个箭头函数里面的this,总是指向handler对象。否则,回调函数运行时,this.doSomething这一行会报错,因为此时this指向document对象。this指向的固定化,并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,导致内部的this就是外层代码的this。正是因为它没有this,所以也就不能用作构造函数。由于箭头函数没有自己的this,所以当然不能用call()、apply()、bind()改变this的指向。

6. class

类的方法内部如果含有this,它默认指向类的实例。

class Logger {    /*constructor() {
        this.printName = this.printName.bind(this);
    }*/
    printName(name = 'Nicolas') {        this.print(`Hello ${name}`);
    }
    print(text) {
        console.log(text);
    }
}
const logger = new Logger();
const { printName } = logger;
printName();
Copy after login

上面代码中,printName方法中的this,默认指向Logger类的实例。但是,如果将这个方法提取出来单独使用,this会指向该方法运行时所在的环境,因为找不到print方法而导致报错。一种简单的解决方法就是在构造函数中绑定this。而另一种方法是使用箭头函数:

class Logger {
    constructor() {        this.printName = (name='Nicolas') => {            this.print(`Hello ${name}`);
    }
    print(text) {
        console.log(text);
    }
}
const logger = new Logger();
const { printName } = logger;
printName();
Copy after login

还有一种方法是使用Proxy,获取方法的时候,自动绑定this。

function selfish (target) {
  const cache = new WeakMap();
  const handler = {
    get (target, key) {
      const value = Reflect.get(target, key);      if (typeof value !== 'function') {        return value;
      }      if (!cache.has(value)) {
        cache.set(value, value.bind(target));
      }      return cache.get(value);
    }
  };
  const proxy = new Proxy(target, handler);  return proxy;
}
const logger = selfish(new Logger());
Copy after login

 以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

foreach, for in, for of 之间的异同

Vue+Electron实现简单桌面应用

JS定时器和单线程异步特性

The above is the detailed content of this object in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template