Skip to Content
JavaScript 設計模式
book

JavaScript 設計模式

by Stoyan Stefanov
March 2012
Intermediate to advanced
244 pages
4h 42m
Chinese
GoTop Information, Inc.
Content preview from JavaScript 設計模式
程式碼重用模式
   
143
在這個例子中,
say()
內的 this 指向
two
,因此
this.name
為「another object」。但如果
將函式指標賦值給全域變數,或者你將函式作為回呼傳遞,在這一類的情境中呢?在客戶
端的程式中,有大量的事件和回呼,所以這種情況確實很常發生:
[137]
在上面兩個例子中,
say()
內部的
this
都指向了全域物件,於是整段的結果都不如預
期。你可以使用一個簡單的函式,來將一個物件固定,或者綁定至方法:
這個
bind()
函式接受一個物件
o
和一個方法
m
,將兩者綁定在一起之後回傳一個新的函
式。新的函式可透過 closure 來存取
o
m
。所以即使在
bind()
回傳之後,裡面那個函式
也可以存取指向原本的物件和方法的
o
m
。我們來用
bind()
建立一個新函式看看:
如你所見,即使
twosay()
被建立成一個全域函式,
this
也沒有指向全域物件,而是指向傳
遞給
bind()
two
物件。不論你用什麼方式呼叫
twosay()
,它的
this
永遠都綁定至
two
想要擁有一個奢華的綁定,所需付出的代價僅是一個額外的 closure
Function.prototype.bind()
ECMAScript 5
Function.prototype
中新增了一個
bind()
方法,讓綁定就像使用
apply()
call()
一樣簡單。如此你就可以使用這樣的表示式:
將方法指定給一個變數
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript 之美

JavaScript 之美

Anton Kovalyov
重構 JavaScript

重構 JavaScript

Evan Burchard

Publisher Resources

ISBN: 9789862764190