In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
这篇文章主要讲解了"JavaScript中使用getter和setter实例分析",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"JavaScript中使用getter和setter实例分析"吧!
getter和setter如何工作?
首先小小地总结一下这些是什么东西:
有时候,我们希望能允许访问一个会返回动态计算值的属性,或者你可能想要反映内部变量的状态,而不使用显式的方法调用。
为了说明它们是如何工作的,让我们来看一个有着两个属性的person对象,这两个属性为:firstName和lastName,以及一个计算值:fullName。
var obj = { firstName: "Maks", lastName: "Nemisj" }
计算值fullName会返回firstName和lastName两者的串联。
Object.defineProperty(person, 'fullName', { get: function () { return this.firstName + ' ' + this.lastName; } });
为了得到fullName的计算值,不需要像person.fullName()带可怕的括号,只需要使用简单的var fullName = person.fullName。
这同样适用于setter,你可以通过使用函数设置值:
Object.defineProperty(person, 'fullName', { set: function (value) { var names = value.split(' '); this.firstName = names[0]; this.lastName = names[1]; } });
使用就和getter一样简单:person.fullName = ‘Boris Gorbachev’。这将调用上面定义的函数,并分离Boris Gorbachev成firstName和lastName。
问题在哪里?
你也许在想:"嘿,我喜欢getter和setter方法,它们感觉更自然,就像JSON一样。"你说得对,它们的确是这样的,但是我们先退一步来看一看fullName在getter和setter之前是如何工作的。
为得到值,我们将使用类似于getFullName()的一些东西,以及为了设置值,我们将使用person.setFullName(‘Maks Nemisj’)。
如果拼错函数名,person.getFullName()写成person.getFulName()会发生什么呢?
JavaScript会给出一个错误:
person.getFulName(); ^ TypeError: undefined is not a function
这个错误会在适当的时候适当的地方被触发。访问函数不存在的对象将触发错误--这是好的。
现在,让我们来看看当用错误的名称来使用setter的时候会发生什么?
person.fulName = 'Boris Gorbachev';
什么也没有。对象是可扩展的,可以动态分配键和值,因此不会有错误在运行时被抛出。
这样的行为意味着错误可能显示在用户界面上的某个地方,或者,当某些操作被执行在错误的值上时,而并非是打字错误的时刻。
跟踪应该发生在过去但却显示在将来的代码流上的错误是如此有意思。
seal行不行
这个问题可以通过sealAPI来部分解决。只要对象是密封的,它就不能突变,也就是意味着fulName将试图分配一个新键到person对象,并且它会失败。
出于某种原因,当我在Node.js V4.0测试这个的时候,它没有按照我期待的那样工作。所以,我不能确保这个解决方案。
而更令人沮丧的是,对于setter一点也没有解决方法。正如我前面提到的,对象是可扩展和可故障保护的,这意味着访问一个不存在的键不会导致任何错误。
如果这种情况只适用于对象的文字的话,我不会多此一举地写这篇文章,但在ECMAScript 2015(ES6)和用类定义getter和setter能力的兴起之后,我决定写下关于潜在陷阱的博客。
类的到来
我知道当前类在一些JavaScript社区不是非常受欢迎。人们对在函数式/基于原型的语言,例如JavaScript中是否需要它们,争执不休。然而,事实是,类就在ECMAScript 2015(ES6)规范说明中,并且将存在于此一段时间。
对我来说,类是指定在类的外部世界(消费者)和应用程序的内部世界之间的定义良好的API的一种方式。这就是白纸黑字放入规则的抽象,并且我们假定这些规则不会很快改变。
改进person对象,做一个它的real类。person定义了接口用于获取和设置fullName。
class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } getFullName() { return this.firstName + ' ' + this.lastName; } setFullName(value) { var names = value.split(' '); this.firstName = names[0]; this.lastName = names[1]; } }
类定义了一个严格的接口描述,但getter和setter方法使其变得不太严格。我们已经习惯了臃肿的错误,当工作于对象文字和JSON时的键中出现拼写错误的时候。我希望至少类能够更严格,并且在这个意义上,提供更好的反馈给开发人员。
虽然这种情况在定义getter和setter在一个类上的时候没有任何不同。但它不会阻止任何人拼错。
class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } get fullName() { return this.firstName + ' ' + this.lastName; } set fullName(value) { var names = value.split(' '); this.firstName = names[0]; this.lastName = names[1]; } }
有拼写错误的执行不会给出任何错误:
var person = new Person('Maks', 'Nemisj'); console.log(person.fulName);
同样不严格,不冗长,不可追踪的行为导致可能会出错。
在我发现这一点后,我有一个问题:在使用getter和setter的时候,有没有什么可以做的,以便于使得类更严格?我发现:有是肯定有,但是这值得吗?增加额外层次的复杂性到代码就只是为了使用数量更少的括号?对于API定义,也可以不使用getter和setter,而这样一来就能解决这个问题。除非你是一个铁杆开发人员,并愿意继续进行,不然还有另一种解决方案,如下所述。
proxy来帮助?
除了getter和setter方法,ECMAScript 2015(ES6)还自带proxy对象。proxy可以帮助你确定委托方法,这些委托方法可以在实际访问键执行之前,用来执行各种操作。事实上,它看起来像动态getter / setter方法。
proxy对象可以用来捕捉任何到类的实例的访问,并且如果在类中没有找到预先定义的getter或setter就会抛出错误。
为了做到这一点,必须执行下面两个操作:
创建基于Person原型的getter和setter清单。
创建将测试这些清单的Proxy对象。
让我们来实现它。
首先,为了找出什么样的getter和setter方法可以用在类Person上,可以使用getOwnPropertyNames和getOwnPropertyDescriptor:
var names = Object.getOwnPropertyNames(Person.prototype); var getters = names.filter((name) => { var result = Object.getOwnPropertyDescriptor(Person.prototype, name); return !!result.get; }); var setters = names.filter((name) => { var result = Object.getOwnPropertyDescriptor(Person.prototype, name); return !!result.set; });
在此之后,创建一个Proxy对象:
var handler = { get(target, name) { if (getters.indexOf(name) != -1) { return target[name]; } throw new Error('Getter "' + name + '" not found in "Person"'); }, set(target, name) { if (setters.indexOf(name) != -1) { return target[name]; } throw new Error('Setter "' + name + '" not found in "Person"'); } }; person = new Proxy(person, handler);
现在,只要你尝试访问person.fulName,就会显示Error: Getter "fulName" not found in "Person"的消息。
感谢各位的阅读,以上就是"JavaScript中使用getter和setter实例分析"的内容了,经过本文的学习后,相信大家对JavaScript中使用getter和setter实例分析这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.