javascript函数来模拟类,最佳实践? [英] javascript functions to simulate classes, best practices?

查看:131
本文介绍了javascript函数来模拟类,最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,我可以编写类似下面的函数来模拟类。我想知道这是否是最新的方式。任何评论赞赏。感谢

I noticed that i can write functions like the one below to simulate classes. I want to know if this is the most up-to-date way of doing it. Any comments appreciated. Thanks

function Apple(type) {
                this.type = type;
                this.color = "red";
                this.getInfo = function () {
                    return this.color + ' ' + this.type + ' apple';
                };
            }

            var apple = new Apple('testapple');
            apple.color = 'blue';
            console.log(apple.getInfo());


推荐答案

您的代码运行正常,每个实例都有一个 getInfo 函数。这可以避免。您可以使用以下模式在JS中模拟类。

Your code works fine but not efficient enought as it gives each instance an getInfo function. This could be avoided. You could use the following patterns to simulate classes in JS.

类属性/方法,您可以在构造函数中设置properties / method。

To simulate a class property/method, you set properties/method on the Constructor function.

function Apple() {};
Apple.classProperty = some_value;
Apple.classMethod = some_method;

要模拟实例属性,请在构造函数你在你的代码中):

To simulate an instance property, you set inside the Constructor functions (as you did in your code):

function Apple() {
  this.property = some_instance_value;
};

要模拟实例方法,请在 Constructor.prototype 将在其所有实例之间共享

To simulate an instance method, you setup functions in the Constructor.prototype which will be shared across all its instances

function Apple() {};
Apple.prototype.instanceMethod = function () {...};



高级模式



设置私有/特权方法, Crockford 有非常有用的模式。

Advanced Pattern

If you want to set private/privileged method, Crockford has very useful patterns available.

私有方法 - 仅适用于构造函数:

Private Method - only available to the constructor:

function Constructor(...) {
var that = this;
var membername = value;
function membername(...) {...}

}


$ b b

Privileged方法 - 可以访问私有方法,并且可以访问public:

Privileged Method - can access private method and is accesible to the public:

function Constructor(...) {
this.membername = function (...) {...};
}

这篇关于javascript函数来模拟类,最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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