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

后端 未结 15 1971
被撕碎了的回忆
被撕碎了的回忆 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:34

    Bascially there is no concept of class in JS so we use function as a class constructor which is relevant with the existing design patterns.

    //Constructor Pattern
    function Person(name, age, job){
     this.name = name;
     this.age = age;
     this.job = job;
     this.doSomething = function(){
        alert('I am Happy');
    }
    }
    

    Till now JS has no clue that you want to create an object so here comes the new keyword.

    var person1 = new Person('Arv', 30, 'Software');
    person1.name //Arv
    

    Ref : Professional JS for web developers - Nik Z

提交回复
热议问题