What techniques can be used to define a class in JavaScript, and what are their trade-offs?

后端 未结 19 1464
庸人自扰
庸人自扰 2020-11-22 07:26

I prefer to use OOP in large scale projects like the one I\'m working on right now. I need to create several classes in JavaScript but, if I\'m not mistaken, there are at le

19条回答
  •  无人及你
    2020-11-22 07:54

    Based on the example of Triptych, this might even be simpler:

        // Define a class and instantiate it
        var ThePerson = new function Person(name, gender) {
            // Add class data members
            this.name = name;
            this.gender = gender;
            // Add class methods
            this.hello = function () { alert('Hello, this is ' + this.name); }
        }("Bob", "M"); // this instantiates the 'new' object
    
        // Use the object
        ThePerson.hello(); // alerts "Hello, this is Bob"
    

    This only creates a single object instance, but is still useful if you want to encapsulate a bunch of names for variable and methods in a class. Normally there would not be the "Bob, M" arguments to the constructor, for example if the methods would be calls to a system with its own data, such as a database or network.

    I am still too new with JS to see why this does not use the prototype thing.

提交回复
热议问题