在 Javascript 函数中混合反对表示法和常规样式?

发布于 2024-09-18 23:01:17 字数 709 浏览 6 评论 0原文

对于精通 javascript 程序员的一个小问题:在 javascript 中声明函数有两种方法。

A: javascript-object-notation

function MyLittleHouseA(name) {
    this.age = 88,
    this.name = name,
    this.getName = function()
    {
        return this.name;
    }
}

B: 嗯,正常:

function MyLittleHouseB(name) {
    this.age = 88;
    this.name = name;
    //do some more proceduaral stuff upon 'construction'
    this.age = this.age + 20; 
    this.getName = function()
    {
        return this.name;
    }
}

我发现 A 更优雅(并且有许多我想变成可配置选项的对象......) ,但可能想在实例创建时做更多的事情,因此我确实需要如 B 所示。

这些可以混合吗?

¡ 谢谢!

A small question for versed javascript programmers: There are two ways to declare a function in javascript.

A: javascript-object-notation

function MyLittleHouseA(name) {
    this.age = 88,
    this.name = name,
    this.getName = function()
    {
        return this.name;
    }
}

B: uhm, normal:

function MyLittleHouseB(name) {
    this.age = 88;
    this.name = name;
    //do some more proceduaral stuff upon 'construction'
    this.age = this.age + 20; 
    this.getName = function()
    {
        return this.name;
    }
}

I find A more elegant (and have a number of objects I want to turn into configurable options...), but might want to do some more stuff upon instance creation, hence I do need as shown in B.

Can these be mixed?

¡ Thanx !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纵情客 2024-09-25 23:01:17

您的第一个选项不使用对象表示法。如果您想使用对象表示法,您可以编写如下内容:

function MyLittleHouse(name) {
    var age = 88;
    age += 20;
    return {
        getName: function() {
            return name;
        }
    }
}

这具有不使用 this 的优点,这意味着您可以避免与 this 绑定相关的任何问题。它还隐藏了 agename,这可能是理想的,也可能不是——就目前而言,没有办法访问 age,而 name 是不可变的,因为它只能通过 getName 读取。如果您想将 age 公开为普通字段:

function MyLittleHouse(name) {
    var age = 88;
    age += 20;
    return {
        age: age,
        getName: function() {
            return name;
        }
    }
}

Your first option doesn't use object notation. If you want to use object notation, you could write something like this:

function MyLittleHouse(name) {
    var age = 88;
    age += 20;
    return {
        getName: function() {
            return name;
        }
    }
}

This has the advantage of not using this, which means you avoid any issues with the binding of this. It also hides age and name, which may or may not be desirable -- as it stands, there's no way for age to be accessed, while name is immutable since it can only be read via getName. If you want to expose age as a normal field:

function MyLittleHouse(name) {
    var age = 88;
    age += 20;
    return {
        age: age,
        getName: function() {
            return name;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文