函數方法that與apply

來源:互聯網
上載者:User

標籤:this   數通   xiaomi   表示   一個   應該   通過   can   asc   

方法

在一個對象中綁定函數,稱為這個對象的方法

var xiaoming = {    name: ‘xiaoming‘,    brith: 1997,    age: function(){        var y = new Date().getFullYear();        return y - this.brith;     }} xiaoming.age() // 21

當我們想使用第三方變數替換冗長的xiaoming.age()的時候,我們來看看效果

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

當我們採用第一種寫法的時候實際是將age方法提出來了,那麼this所指向的對象也變成了window,故表示NaN
那麼為了避免被外部調用,並且可以迴圈使用其age()我們引入that

‘use strict‘var xiaoming = {    brith: 1997,    age: function(){        // 從方法一開始就擷取this        that = this;        function getAgeFromBrith() {            var y = new Date.getFullYear();            return y - that;             }            return getAgeFromBrith();    }}xiaoming.age(); // 21var fn = xiaoming.age;fn(); // Uncaught TypeError: Cannot read property ‘birth‘ of undefined




apply與call

我們知道函數通過this來指代對象,那如果我們想指代某一對象應該如何操作呢?
這時候就可以使用applycell

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

appay | call 區別

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




裝飾器

裝飾器多用於將函數進行改造更名,如改造alert使其具有彈窗與控制台雙重功能

// 儲存原來的 alertvar oldAlert = alert;window.alert = function() {    alert(this);    console.log(this);    return oldAlert.apply(null, arguments); }alert("halo")

函數方法that與apply

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.