JavaScript Design Patterns and Development practices | this, call, and apply

Source: Internet
Author: User
<span id="Label3"></p><p><p>Original Address: http://segmentfault.com/a/1190000003959359</p></p><p><p></p></p>This<p><p>The This of JavaScript always points to an object, and to which object it is dynamically bound at run time based on the execution environment of the function, not the environment when the function is Declared.</p></p>The point of this<p><p>The point of this can be broadly divided into the following 4 categories:</p></p> <ul> <ul> <li><p>Method invocation as an object</p></li> <li><p>Called as a normal function</p></li> <li><p>Constructor call</p></li> <li><p><code>Function.prototype.call</code>or <code>Function.prototype.apply</code> call</p></li> </ul> </ul><p><p><strong>1. Method calls as objects</strong></p></p><p><p>When a function is called as a method of an object, this points to the Object:</p></p><pre><pre><code class="js"><span class="hljs-comment">// 声明obj对象<span class="hljs-keyword">var obj = { a: <span class="hljs-string">‘a属性的值‘, <span class="hljs-comment">// a 属性 getA: <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){ <span class="hljs-comment">// getA()方法 <span class="hljs-built_in">console.log(<span class="hljs-keyword">this === obj); <span class="hljs-comment">// 输出:true <span class="hljs-built_in">console.log(<span class="hljs-keyword">this.a); <span class="hljs-comment">// 输出: a属性的值 }};obj.getA();</span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre><p><p><strong>2. As a normal function call</strong></p></p><p><p>When a function is not invoked as a property of an object, that is, in the normal function, this points to the global Object. In the Browser's javascript, the Global object is the window Object.</p></p><pre><pre> <code class="js"><span class="hljs-built_in">window.name = <span class="hljs-string"> ' globalname '; <span class="hljs-comment">//declares The Global Object's Name property <span class="hljs-keyword">var getName = <span class="hljs-function">< Span class= "hljs-keyword" >function<span class="hljs-params"> () {<span class="hljs-comment">//define getname () function <span class="hljs-keyword">return <span class="hljs-keyword">this.name;}; <span class="hljs-comment">//call function <span class="hljs-built_in">console.log (getName ()); <span class="hljs-comment">//output: globalname </span> </span> </span> </span> </span> </span> </span> </span> </span> </span> </span> </span></code></pre></pre><pre><pre><code class="js"><span class="hljs-built_in">window.name = <span class="hljs-string">‘globalName‘; <span class="hljs-comment">// 声明全局对象的name属性<span class="hljs-keyword">var myObject = { <span class="hljs-comment">// 声明myObject对象 name: <span class="hljs-string">‘objectName‘; getName: <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){ <span class="hljs-comment">// 定义getName()方法 <span class="hljs-keyword">return <span class="hljs-keyword">this.name; }}<span class="hljs-keyword">var getName = myObject.getName; <span class="hljs-comment">// 将getName()方法赋给变量getName<span class="hljs-built_in">console.log(getName()); <span class="hljs-comment">// 输出: globalName</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre><p><p><strong>3. constructor invocation</strong></p></p><p><p>JavaScript does not have a class, but you can create objects from the constructor and also provide a new operator to call the Constructor.</p></p><p><p>Most JavaScript functions can be used as Constructors. The Constructor's appearance is the same as the normal function, and their difference is in the way they are called. That is, when an object is created with the new operator, it is called by the function as a constructor. When a function is called with the new operator, the function always returns an object, at which point this is directed to the returned Object.</p></p><pre><pre><code class="js"><span class="hljs-keyword">var myClass = <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){ <span class="hljs-keyword">this.name = <span class="hljs-string">‘className‘;};<span class="hljs-keyword">var obj = <span class="hljs-keyword">new myClass();<span class="hljs-built_in">console.log(obj.name); <span class="hljs-comment">// 输出:seven</span></span></span></span></span></span></span></span></span></span></code></pre></pre><p><p>however, if the constructor explicitly returns an object of type objects, This function returns an object of the type objects, not the object defined by the function itself, for example:</p></p><pre><pre><code class="js"><span class="hljs-keyword">var myClass = <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){ <span class="hljs-keyword">this.name = <span class="hljs-string">‘className‘; <span class="hljs-keyword">return { <span class="hljs-comment">//显式地返回一个对象 name: <span class="hljs-string">‘anne‘ }};<span class="hljs-keyword">var obj = <span class="hljs-keyword">new myClass();<span class="hljs-built_in">console.log(obj.name); <span class="hljs-comment">// 输出:anne</span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre><p><p>and, if the constructor does not explicitly return any data, or returns a non-object type of data, this situation does not occur.</p></p><pre><pre><code class="js"><span class="hljs-keyword">var myClass = <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){ <span class="hljs-keyword">this.name = <span class="hljs-string">‘className‘; <span class="hljs-keyword">return <span class="hljs-string">‘anne‘; <span class="hljs-comment">// 返回string类型};<span class="hljs-keyword">var obj = <span class="hljs-keyword">new myClass();<span class="hljs-built_in">console.log(obj.name); <span class="hljs-comment">// 输出:className</span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre><p><p><strong>4.function.prototype.call or Function.prototype.apply call</strong></p></p><p><p>This <code>Function.prototype.call</code> is used or <code>Function.prototype.apply</code> can be changed dynamically in relation to a normal function call.</p></p><pre><pre><code class="js"><span class="hljs-keyword">var A = { name: <span class="hljs-string">‘ObjectA‘, getName: <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){ <span class="hljs-keyword">return <span class="hljs-keyword">this.name; }};<span class="hljs-keyword">var B = { name: <span class="hljs-string">‘ObjectB‘};<span class="hljs-built_in">console.log(A.getName()); <span class="hljs-comment">// 作为对象的方法调用,输出:ObjectA<span class="hljs-built_in">console.log(A.getName.call(B)); <span class="hljs-comment">// 输出:ObjectB</span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre>The missing this<p><p>We often see a undefined situation because this point is different from our expectations, for example:</p></p><pre><pre><code class="js"><span class="hljs-keyword">var obj = { name: <span class="hljs-string">‘objName‘; getName: <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){ <span class="hljs-keyword">return <span class="hljs-keyword">this.name; }};<span class="hljs-comment">// 作为对象的方法调用,指向obj对象<span class="hljs-built_in">console.log(obj.getName()); <span class="hljs-comment">// 输出:objName<span class="hljs-comment">// 作为普通函数调用,指向全局对象window,name属性尚未定义<span class="hljs-keyword">var getName2 = obj.getName;<span class="hljs-built_in">console.log(getName2()); <span class="hljs-comment">// 输出:Lundefined</span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre>Call and apply<p><p>ECAMSCRIPT3 defines two methods for the prototype of a Function, namely, Function.prototype.call or Function.prototype.apply. In some functional style code writing, the call and apply methods are particularly Useful.</p></p>The difference between call and apply<p><p>The function of Function.prototype.call or Function.prototype.apply is exactly the same, and the difference is only in the form of incoming Parameters.</p></p><p><p>Apply accepts two parameters, the first parameter sets the pointer to the this <strong>object in the function body</strong> , and the second function is an indexed collection, which can be an array or an array of classes. The Apply method passes the elements in this collection as arguments to the called Function.</p></p><pre><pre><code class="js"><span class="hljs-keyword">var func = <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(a, b, c){ <span class="hljs-built_in">console.log([a, b, c]); <span class="hljs-comment">// 输出:[1,2,3]};func.apply(<span class="hljs-literal">null, [<span class="hljs-number">1, <span class="hljs-number">2, <span class="hljs-number">3]);</span></span></span></span></span></span></span></span></span></span></code></pre></pre><p><p>The number of parameters called by call is not fixed, the first parameter also represents this point in the body of the function, and after the second argument, each parameter is passed into the function sequentially:</p></p><pre><pre><code class="js"><span class="hljs-keyword">var func = <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(a, b, c){ <span class="hljs-built_in">console.log([a, b, c]); <span class="hljs-comment">// 输出:[1,2,3]};func.call(<span class="hljs-literal">null, <span class="hljs-number">1, <span class="hljs-number">2, <span class="hljs-number">3);</span></span></span></span></span></span></span></span></span></span></code></pre></pre><p><p>When invoking a function, the JavaScript interpreter does not care about the difference in the number, type, and order of formal parameters and arguments, and Javascript's arguments are internally represented by an array. In this sense, apply is higher than the use of call, we do not have to care about how many parameters are passed in the function, as long as apply a brain to push the Past.</p></p><p><p>When using call or apply, if the first argument we pass in is null, this in the body of the function points to the default host object, which is window in the Browser:</p></p><pre><pre><code class="js"><span class="hljs-keyword">var func = <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(a, b, c){ <span class="hljs-built_in">console.log(<span class="hljs-keyword">this);};func.apply(<span class="hljs-literal">null, [<span class="hljs-number">1, <span class="hljs-number">2, <span class="hljs-number">3]); <span class="hljs-comment">//输出:window对象func.call(<span class="hljs-literal">null, <span class="hljs-number">1, <span class="hljs-number">2, <span class="hljs-number">3); <span class="hljs-comment">//输出:window对象</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre>Use of call and apply <ul> <ul> <li><p>Change this point</p></li> <li><p>Function.prototype.bind</p></li> <li><p>Ways to borrow other objects</p></li> </ul> </ul><p><p><strong>1. Change this point</strong></p></p><p><p>The most common use of call and apply is to change the this point inside the function:</p></p><pre><pre><code class="js"><span class="hljs-keyword">var A = { name: <span class="hljs-string">‘nameA‘;};<span class="hljs-keyword">var B = { name: <span class="hljs-string">‘nameB‘;};<span class="hljs-built_in">window.name = <span class="hljs-string">‘nameWindow‘;<span class="hljs-keyword">var getName = <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params">(){ conlole.log(<span class="hljs-keyword">this.name);};getName(); <span class="hljs-comment">// 以普通函数调用,指向了window对象,输出:nameWindowgetName.call(A); <span class="hljs-comment">// 改变了this的指向,指向了传入的对象,输出:nameAgetName.call(B); <span class="hljs-comment">// 改变了this的指向,指向了传入的对象,输出:nameB</span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre><p><p><strong>2.function.prototype.bind</strong></p></p><p><p>Most advanced browsers implement a built-in Function.prototype.bind that specifies the this point within the Function.<br>If there is no native Function.prototype.bind implementation, you can simulate one by:</p></p><pre><code class="js"><span class="hljs-built_in">Function.prototype.bind =<span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params"><span class="hljs-keyword" (context) {<span>var self = <span class="hljs-keyword">this; <span class="hljs-comment">//save original function <span class="hljs-keyword">return <span class="hljs-function"> <span class="hljs-keyword">function<span class="hljs-params"> () {<span class="hljs-comment">//returns a new function <span class="hljs-keyword">return self.apply (context, <span class="hljs-built_in">arguments); <span class="hljs-comment">//executes The new function, the previously passed context is treated as this} in the new function body; <span class="hljs-keyword">var obj = {name: <span class="hljs-string"> "objname"};<span class="hljs-keyword"> var func = <span class="hljs-function"><span class="hljs-keyword">function<span class="hljs-params"> () {<span class="hljs-built_in">console.log (<span class="hljs-keyword">this.name); <span class="hljs-comment">//output: objname}.bind (obj); func (); </span> </span> </span> </span> </span> </span> </span> </span> </span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre><p><p> JavaScript Design Patterns and Development practices | this, call, and apply </p> </p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.