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

后端 未结 19 1703
庸人自扰
庸人自扰 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 08:05

    Here's the way to do it without using any external libraries:

    // 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"
    

    Now the real answer is a whole lot more complex than that. For instance, there is no such thing as classes in JavaScript. JavaScript uses a prototype-based inheritance scheme.

    In addition, there are numerous popular JavaScript libraries that have their own style of approximating class-like functionality in JavaScript. You'll want to check out at least Prototype and jQuery.

    Deciding which of these is the "best" is a great way to start a holy war on Stack Overflow. If you're embarking on a larger JavaScript-heavy project, it's definitely worth learning a popular library and doing it their way. I'm a Prototype guy, but Stack Overflow seems to lean towards jQuery.

    As far as there being only "one way to do it", without any dependencies on external libraries, the way I wrote is pretty much it.

提交回复
热议问题