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

后端 未结 19 1491
庸人自扰
庸人自扰 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:45

    var Student = (function () {
        function Student(firstname, lastname) {
            this.firstname = firstname;
            this.lastname = lastname;
            this.fullname = firstname + " " + lastname;
        }
    
        Student.prototype.sayMyName = function () {
            return this.fullname;
        };
    
        return Student;
    }());
    
    var user = new Student("Jane", "User");
    var user_fullname = user.sayMyName();
    

    Thats the way TypeScript compiles class with constructor to JavaScript.

提交回复
热议问题