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 設計模式
142
   
第六章
範例:向陣列借用方法
此模式的一種常見的用法是,向陣列借用方法。
陣列有些很有用的方法,而在一些類陣列的物件例如
arguments
中則沒有這些方法。於是
arguments
就可以向陣列借用,例如
slice()
方法。這裡有個例子:
在本範例中,有個空陣列被建立出來,只是為了使用它的方法。另一個稍微長一點的方
式,是直接向陣列的原型借用方法,使用
Array.prototype.slice.call(...)
。這方式需
要多輸入長一點,但你可以省下建立空陣列的運算。
借用並綁定
不論是透過
call()
/
apply()
,或者簡單的賦值來借用方法,方法內
this
所指向的物件,
都是倚賴呼叫運算式來決定。但有的時候,最好讓
this
的值「鎖住」,或者是綁定至一
個特定的物件,並且是預先就決定好的。
我們來看一個範例,有個物件
one
,它有個
say()
方法:
現在有個
two
沒有
say()
方法,但它可以從
one
那邊借用:
試用
範例
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