"JavaScript Design Patterns and development" note 3.call and apply

Source: Internet
Author: User

    • 1. Change this point
    • 2.function.prototype.bind
    • 3. Borrowing other object methods
      • 1. Borrowing to implement inheritance
      • 2. To achieve nausea
        • Array.prototype.push.call
        • Array.prototype.join.call
        • Array.prototype.slice.call
        • Object.prototype.toString.call
1. Change this point
var obj1 = {    name:"Bob Marley"}; var obj2 = {    name:"Bob Dylan"}; var name = "David Bowie"; var function () {    Console.log (this. name);} GetName ();   // output undefined // output Bob Marley // output Bob Dylan

In real-world development, you will often encounter this point to a scene that has been inadvertently changed: for example:

document.getElementById (' Div1 '). onclick=function() {    alert (this. id);         // Output Div1    var function () {        alert (this. id);     // output undefined     }    func ();};

Use call to fix this in the Func function to point to the DIV

document.getElementById (' Div1 '). onclick=function() {    alert (this. ID);     var function () {        alert (this. id);    }    Func.call (this);}; Again such as:var name = "Smartom"; var function () {    Console.log (this. name);} Func ();

Use call to fix this in the Func function so that it points to the div again, such as:

var obj ={    "Smartom"}varfunction() {    Console.log (  This . name);} Func.call (obj);

2.function.prototype.bind

Most browsers implement the built-in Function.prototype.bind, which specifies that this point inside the function can be simulated even without the native Function.prototype.bind implementation, for example:

//在一些浏览器中可以忽略 bind函数
Function.prototype.bind =function(context) {var_self = This; return function(){        return_self.apply (context,arguments); }}varobj ={name:"Smartom"}varFunc =function() {Console.log ( This. name);}.            Bind (obj); //to bindFunc ();

 
3. Ways to borrow other objects "implement inheritance"

1. Borrowing to implement inheritance

varA =function(name) {//Parent Class A     This. Name =name;}varB =function(){//Subclass B Inherits parent Class AA.apply ( This, arguments);} B.prototype.getname=function(){//B Method    return  This. Name;varb =NewB (' Asdfasdfasdf ')); Console.log (B.getname ());

2. Implement

Array.prototype.push.callArray.prototype.join.callArray.prototype.slice.callObject.prototype.toString.call ( )1. Array.prototype.push.callArray.prototype.push.call (obj,arguments) equals var html=[]; Html.push (that large pile)<script type= "Text/javascript" >    (function () {        varCustomservice =function () {        }; Customservice.prototype={open:function() {contents: This. _gethtml (),}, close:function() {}, _gethtml:function () {                varHTML = []; Array.prototype.push.call (HTML,' <div class=\ ' content\ ' > ',                        ' <div>1, </div> ',                        ' <div>2, <\/div> ',                        ' <div>3, <\/div> ',                        ' <div>4, <\/div> ',                    ' <\/div> '                ); returnHtml.join (' ');        }        }; Window. Customservice=NewCustomservice (); })();</script>2. Array.prototype.join.call//arguments is equivalent to an array of objectsArray.prototype.join.call (arguments, ', ') is similar to the Window.join method. Apply,call does not change scope, can refer to the contents of finally<script type= "Text/javascript" >varJoin =function () {     for(vari = 0, b = "; I < This. length; i + +) {        if(i) b+= arguments[0]; b+= This[i]; }    returnb;}; varShow =function () {    //new Array (arguments)). Join ('_');    //Try    Try{alert (array.apply (NULL, arguments). Join (' _ ')        ); returnJoin.call (arguments, '-');//Array.prototype.join is similar to the Window.join method. Apply,call does not change scope, can refer to the contents of finally}finally {        varFunc =function() {alert (a);         }; void function () {            varA = 1; Try{Func.call ( This); } Catch(exp) {alert (exp.message);    }        }(); }}; Alert (Show (1, 2, 3, 5));</script>3. Array.prototype.slice.callvara={length:2,0: ' First ', 1: ' Second '}; Array.prototype.slice.call (a);//["First", "second"]varA={length:2}; Array.prototype.slice.call (a);//[Undefined, undefined]probably just started to learn JS's children's shoes do not quite understand why this can achieve such a function. For example, I am a, so, to explore. First of all, slice has two usages, one is String.slice, the other is Array.slice, the first one returns the string, the second is the array, and here we see 2nd. Array.prototype.slice.call (arguments) is able to turn arguments into a group, then Arguments.toarray (). Slice (); here it is. Is it possible to say that the process of Array.prototype.slice.call (arguments) is to convert the first parameter passed in to an array before calling slice? 4. Object.prototype.toString.call uses the native toString () method on Object.prototype to determine the data type, using the following method: Object.prototype.toString.call ( Value)1. Judgment base type: Object.prototype.toString.call (NULL);//"[Object Null]"Object.prototype.toString.call (undefined);//"[Object Undefined]"Object.prototype.toString.call ("abc");//"[Object String]"Object.prototype.toString.call (123);//"[Object number]"Object.prototype.toString.call (true);//"[Object Boolean]"2. Determine the native Reference type: function type functions fn () {Console.log ("Test");} Object.prototype.toString.call (FN);//"[Object Function]"Date TypevarDate =Newdate (); Object.prototype.toString.call (date);//"[Object Date]"Array Typevararr = [A.];object.prototype.tostring.call (arr);//"[Object Array]"Regular ExpressionsvarReg =/[hbc]at/Gi;object.prototype.tostring.call (arr);//"[Object Array]"Custom TypesfunctionPerson (name, age) { This. Name =name;  This. Age =Age ;}varperson =NewPerson ("Rose", 18); Object.prototype.toString.call (arr); //"[Object Object]"It is clear that this method does not accurately judge that a person is an instance of the person class, but can only be judged with the instanceof operator, as follows: Console.log ( personinstanceofperson);//output is True3. Determine the native JSON object:varIsnativejson = window. JSON &&Object.prototype.toString.call (JSON); Console.log (Isnativejson);//The output is "[Object JSON]" stating that the JSON is native, otherwise it is not;Note: The Object.prototype.toString () itself is allowed to be modified, and the application we are discussing now about Object.prototype.toString () is assumed to be toString () Method has not been modified as a prerequisite. 

"JavaScript Design Patterns and development" note 3.call and apply

Related Article

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.