function methods that and apply

Source: Internet
Author: User

Method

A method that binds a function in an object called this object

var  xiaoming Span class= "OP" >=  { name  :   ' xiaoming '   brith  :  Span class= "DV" >1997   age  :  function  () { var  y =  
     
      new 
      date  (). getfullyear         ()  return  y - this . brith       }  }  xiaoming . age  () //  

When we want to replace the lengthy with a third-party variable xiaoming.age() , let's look at the effect

// 写法1=xiaoming.age;fn()  // NaN// 写法2=xiaoming.age();// 21

When we use the first form of writing, the Age method is actually proposed, then the this object pointed to becomes window , so thatNaN
So in order to avoid being called externally, and you can recycle it, age() we introducethat

' use strict 'varXiaoming= {    Brith: 1997,     Age: function(){        //Get this from the beginning of the methodThat=  This;        function Getagefrombrith(){            varY= New Date.getFullYear();            returnY-That;             }            return Getagefrombrith();    }}xiaoming. Age(); //varFn= xiaoming. Age;fn(); //uncaught Typeerror:cannot Read Property ' birth ' of undefined




Apply and call

We know that a function this is meant to refer to an object, so what if we want to refer to what an object should do?
This can be used apply with cell the

functiongetAge{returnthis.age;}var={    name:‘kaso‘,    age:20}getAge.apply(xiaoming, []);//20getAge.call(xiaoming, []);  //20

Appay | Call Difference

//调用Math.max(3, 4, 5)Math.max.apply(null, [3,4,5// 5Math.max.call(null,3,4,5)  // 5




Decorative Device

Adorners are used to rename functions, such as the transformation of the alert window and console with the dual function

// 保存原来的 alertvar= alert;window.alert=function{    alert(this);    console.log(this);    returnoldAlert.apply(null, arguments);}alert("halo")

function methods that and apply

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.