Skip to Content
JavaScript 经典实例:第三版
book

JavaScript 经典实例:第三版

by Adam D. Scott, Matthew MacDonald, Shelley Powers
September 2022
Intermediate to advanced
585 pages
8h 17m
Chinese
China Electric Power Press Ltd.
Content preview from JavaScript 经典实例:第三版
188
7
Object.seal()
禁止添加、删除或配置属性。不过,仍然可以设定属性的值。经常用于捕获为
不存在的属性赋值,这种行为正常情况下保持静默。
Object.freeze()
禁止对属性做任何形式的修改。无法配置属性、添加新属性或设定属性的值。
对象变成不可变的。
在严格模式下(始终应该开启,除非是在控制台中编写测试代码),试图修改被冻
结的对象将抛出
TypeError
异常。如果没有使用严格模式,修改属性也将失败,但
是悄无声息,属性原来的值保持不变,代码继续运行。
你可以使用配套
Object.isFrozen()
方法检查对象有没有冻结。
if
(Object.isFrozen(obj)) ...
7.9
使用代理截取并改变对象上的操作
7.9.1
问题
你想在对象执行特定操作时运行代码,但是你不想把代码放在对象中。
7.9.2
方案
使用
Proxy
类可以截取对象上的各种操作。下述示例使用代理验证名为
product
对象,确保不能使用不存在的属性,也不能为数字类型设置数字以外的值。
//
这是使用代理监视的对象
const
product = {name: 'banana'};
//
一个供代理使用的处理函数,用于截取有问题的操作
const
propertyChecker = {
set:
function
(target, property, value) {
if
(property === 'price') {
if
(
typeof
value !== 'number') {
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

T. J. Crowder
JavaScript

JavaScript

David Flanagan
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9787519869601