How to “properly” create a custom object in JavaScript?

后端 未结 15 1983
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 08:07

I wonder about what the best way is to create an JavaScript object that has properties and methods.

I have seen examples where the person used var self = this<

15条回答
  •  遇见更好的自我
    2020-11-21 08:48

    You can also try this

        function Person(obj) {
        'use strict';
        if (typeof obj === "undefined") {
            this.name = "Bob";
            this.age = 32;
            this.company = "Facebook";
        } else {
            this.name = obj.name;
            this.age = obj.age;
            this.company = obj.company;
        }
    
    }
    
    Person.prototype.print = function () {
        'use strict';
        console.log("Name: " + this.name + " Age : " + this.age + " Company : " + this.company);
    };
    
    var p1 = new Person({name: "Alex", age: 23, company: "Google"});
    p1.print();
    

提交回复
热议问题