JS 可以有与属性相同的 getter 和 setter 方法吗? [英] Can JS have getters and setters methods named same as property?

查看:51
本文介绍了JS 可以有与属性相同的 getter 和 setter 方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在代码中实现类似 down 的行为:

I want to achieve behaviour like down in code:

function Foo(name) {
    this.name = name;
};

var myFoo = new Foo('myName');

myFoo.name('newMyName'); // sets myFoo.name = 'newMyName'
myFoo.name(); // returns 'myName'

但很明显,在这种情况下,我用 name 函数覆盖了 name 属性.无论如何有可能实现该功能?

But it is obvious that in that case I'm overridding name property with name function. Is anyhow possible to achieve that functionality?

推荐答案

当谈论 javascript 中的 getter 和 setter 时,您可能在谈论两个概念之一:

When talking about getters and setters in javascript you may be talking about one of two concepts:

您的问题中的代码说明了这种情况.在这种情况下,一个对象的属性就是一个属性,它可以是一个对象或一个函数.javascript 在同一个命名空间中跟踪两者.事实上,函数只是 javascript 中的对象,因此没有像 C 这样的语言中那样的函数的单独命名空间的概念.

This is the case illustrated by the code in your question. In this case, an object's property is simply that, a property which may or be either an object or a function. javascript keeps track of both within the same namespace. Indeed, functions are just objects in javascript so there is no concept of a separate namespace for functions like you'd find in languages like C.

在这种情况下,getter"和setter"只是常规函数,因此需要单独存储值.围绕这一点有多种策略.

In this case "getters" and "setters" are just regular functions so the value needs to be stored separately. There are several strategies around this.

一种是使用 Java 中常见的隐式 getSomething()setSomething() 样式函数.这允许您从属性名称中消除 getter 和 setter 的歧义,因为 getter 和 setter 在名称中添加了单词get"和set".

One is to use implicit getSomething() and setSomething() style functions commonly found in Java. This allows you to disambiguate the getters and setters from the property name since the getters and setters have the word "get" and "set" added to the name.

第二种策略是您在问题中所写的策略.在这种情况下,您需要将属性存储在另一个名称中,以免与 getter/setter 共享相同的名称.

The second strategy is the one you've written in your question. In this case you need to store the property in another name so as not to share the same name with the getter/setter.

第三种策略是将值存储在闭包中:

The third strategy is to store the value in a closure:

    function Foo (name) {
        var name = name;
        this.name = function (str) {
            if (str !== undefined) name = str;
            return name;
        }
    }

请注意,在上面的代码中,值存储在 name 中,但 getter/setter 是 this.name,这是一个完全不同的变量.这允许您的示例代码按预期工作:

Note that in the code above the value is stored in name but the getter/setter is this.name which is a completely different variable. This allows your example code to work as you expected:

    var me = new Foo('Mark');
    me.name(); // returns Mark
    me.name('Andy'); // sets name to Andy

2.getter 和 setter 作为 javascript 中的一种机制.

这是遵循 ECMAscript 5 规范的较新版本 javascript 的一项功能.此功能允许属性在读取或写入时执行代码,类似于 DOM 对象的 .innerHTML 属性在向其分配内容时调用 HTML 解析器的方式.

2. Getters and setters as a mechanism in javascript.

This is a feature of newer versions of javascript that follows the ECMAscript 5 specification. This feature allows properties to execute code when reading or writing to it similar to how the .innerHTML property of DOM object invokes the HTML parser when you assign something to it.

getter 和 setter 的语法类似于函数,但引入了 getset 关键字来代替 function.

The syntax of getters and setters is similar to functions but introduces the get and set keywords in place of function.

带有 getter 和 setter 的属性的简单示例:

A simple example of a property with getter and setter:

    var me = {
        first_name : "",
        last_name : "",
        get name() {
            return this.first_name + " " + this.last_name;
        },
        set name(str) {
            var n = str.split(/\s+/);
            this.first_name = n.shift();
            this.last_name = n.join(' ');
        }
    }

上面的代码允许您将获取和设置 first_namelast_name 的函数视为变量而不是函数.要使用 name getter 和 setter,您只需执行以下操作:

The code above allows you to treat the functions to get and set the first_name and last_name as if it is a variable instead of a function. To use the name getter and setter you'd simply do:

    me.name = "James Bond";
    alert(me.first_name); // should alert James
    alert(me.last_name); // should alert Bond
    me.last_name = "Dean";
    alert(me.name); // should alert James Dean

使用 javascript get/set 机制,您不能将值存储在使用相同名称的对象中. 例如:

    var foo = {
        set bar(x) {this.bar=x}
    }

上面的代码会编译但尝试设置bar:foo.bar = 1 会因为无限循环导致堆栈溢出 - this.bar= 里面setter 会再次调用 setter.

The code above will compile but trying to set bar: foo.bar = 1 will cause a stack overflow because of the infinite loop - the this.bar= inside the setter will call the setter again.

这篇关于JS 可以有与属性相同的 getter 和 setter 方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆