我更喜欢在大型项目中使用OOP,比如我现在正在做的项目。我需要在JavaScript中创建几个类,但是,如果我没有弄错的话,至少有几种方法可以做到这一点。它的语法是什么,为什么要这样做?

我希望避免使用第三方库——至少一开始是这样。 为了寻找其他答案,我找到了一篇文章《JavaScript面向对象编程,第一部分:继承- JavaScript文档》,它讨论了JavaScript中的面向对象编程。是否有更好的继承方式?


当前回答

你可能想通过使用折叠模式来创建一个类型:

    // Here is the constructor section.
    var myType = function () {
        var N = {}, // Enclosed (private) members are here.
            X = this; // Exposed (public) members are here.

        (function ENCLOSED_FIELDS() {
            N.toggle = false;
            N.text = '';
        }());

        (function EXPOSED_FIELDS() {
            X.count = 0;
            X.numbers = [1, 2, 3];
        }());

        // The properties below have access to the enclosed fields.
        // Careful with functions exposed within the closure of the
        // constructor, each new instance will have it's own copy.
        (function EXPOSED_PROPERTIES_WITHIN_CONSTRUCTOR() {
            Object.defineProperty(X, 'toggle', {
                get: function () {
                    var before = N.toggle;
                    N.toggle = !N.toggle;
                    return before;
                }
            });

            Object.defineProperty(X, 'text', {
                get: function () {
                    return N.text;
                },
                set: function (value) {
                    N.text = value;
                }
            });
        }());
    };

    // Here is the prototype section.
    (function PROTOTYPE() {
        var P = myType.prototype;

        (function EXPOSED_PROPERTIES_WITHIN_PROTOTYPE() {
            Object.defineProperty(P, 'numberLength', {
                get: function () {
                    return this.numbers.length;
                }
            });
        }());

        (function EXPOSED_METHODS() {
            P.incrementNumbersByCount = function () {
                var i;
                for (i = 0; i < this.numbers.length; i++) {
                    this.numbers[i] += this.count;
                }
            };
            P.tweak = function () {
                if (this.toggle) {
                    this.count++;
                }
                this.text = 'tweaked';
            };
        }());
    }());

该代码将为您提供一个名为myType的类型。它将有内部私有字段toggle和text。它还将有这些公开的成员:字段count和numbers;属性toggle, text和numberLength;方法incrementNumbersByCount和tweak。

折叠模式的详细信息如下: Javascript折叠模式

其他回答

下面是不使用任何外部库的方法:

// Define a class like this
function Person(name, gender){

   // Add object properties like this
   this.name = name;
   this.gender = gender;
}

// Add methods like this.  All Person objects will be able to invoke this
Person.prototype.speak = function(){
    alert("Howdy, my name is" + this.name);
};

// Instantiate new objects with 'new'
var person = new Person("Bob", "M");

// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"

真正的答案要比这复杂得多。例如,在JavaScript中没有类这种东西。JavaScript使用基于原型的继承方案。

此外,还有许多流行的JavaScript库,它们在JavaScript中具有类似类的功能。您至少需要了解Prototype和jQuery。

决定哪一个是“最好的”是在Stack Overflow上开始一场圣战的好方法。如果您正在着手一个较大的javascript较多的项目,那么学习一个流行的库并按照它们的方式来做绝对是值得的。我是一个原型的人,但Stack Overflow似乎倾向于jQuery。

至于只有“一种方法可以做到这一点”,不依赖任何外部库,我写的方法就差不多了。

你可能想通过使用折叠模式来创建一个类型:

    // Here is the constructor section.
    var myType = function () {
        var N = {}, // Enclosed (private) members are here.
            X = this; // Exposed (public) members are here.

        (function ENCLOSED_FIELDS() {
            N.toggle = false;
            N.text = '';
        }());

        (function EXPOSED_FIELDS() {
            X.count = 0;
            X.numbers = [1, 2, 3];
        }());

        // The properties below have access to the enclosed fields.
        // Careful with functions exposed within the closure of the
        // constructor, each new instance will have it's own copy.
        (function EXPOSED_PROPERTIES_WITHIN_CONSTRUCTOR() {
            Object.defineProperty(X, 'toggle', {
                get: function () {
                    var before = N.toggle;
                    N.toggle = !N.toggle;
                    return before;
                }
            });

            Object.defineProperty(X, 'text', {
                get: function () {
                    return N.text;
                },
                set: function (value) {
                    N.text = value;
                }
            });
        }());
    };

    // Here is the prototype section.
    (function PROTOTYPE() {
        var P = myType.prototype;

        (function EXPOSED_PROPERTIES_WITHIN_PROTOTYPE() {
            Object.defineProperty(P, 'numberLength', {
                get: function () {
                    return this.numbers.length;
                }
            });
        }());

        (function EXPOSED_METHODS() {
            P.incrementNumbersByCount = function () {
                var i;
                for (i = 0; i < this.numbers.length; i++) {
                    this.numbers[i] += this.count;
                }
            };
            P.tweak = function () {
                if (this.toggle) {
                    this.count++;
                }
                this.text = 'tweaked';
            };
        }());
    }());

该代码将为您提供一个名为myType的类型。它将有内部私有字段toggle和text。它还将有这些公开的成员:字段count和numbers;属性toggle, text和numberLength;方法incrementNumbersByCount和tweak。

折叠模式的详细信息如下: Javascript折叠模式

如果你想要简单,你可以完全避免“new”关键字,只使用工厂方法。有时我更喜欢这样,因为我喜欢使用JSON创建对象。

function getSomeObj(var1, var2){
  var obj = {
     instancevar1: var1,
     instancevar2: var2,
     someMethod: function(param)
     {  
          //stuff; 
     }
  };
  return obj;
}

var myobj = getSomeObj("var1", "var2");
myobj.someMethod("bla");

不过,我不确定大对象的性能会受到什么样的影响。

MooTools(我的面向对象工具)以类的思想为中心。您甚至可以通过继承来扩展和实现。

一旦掌握了它,就会产生可重用的强大javascript。

我认为你应该阅读Douglas Crockford的《JavaScript中的原型继承》和《JavaScript中的经典继承》。

来自他的页面的例子:

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

效果吗?它将允许你以更优雅的方式添加方法:

function Parenizor(value) {
    this.setValue(value);
}

Parenizor.method('setValue', function (value) {
    this.value = value;
    return this;
});

我也推荐他的视频: 先进的JavaScript。

你可以在他的个人主页http://javascript.crockford.com/上找到更多视频 在John Reisig的书中,你可以从Douglas Crockfor的网站上找到许多例子。