What is the use of the init() usage in JavaScript?

后端 未结 3 447
星月不相逢
星月不相逢 2021-01-29 20:21

What is the meaning and usage of the init() function in JavaScript?

3条回答
  •  失恋的感觉
    2021-01-29 20:42

    In JavaScript when you create any object through a constructor call like below

    step 1 : create a function say Person..

    function Person(name){
    this.name=name;
    }
    person.prototype.print=function(){
    console.log(this.name);
    }
    

    step 2 : create an instance for this function..

    var obj=new Person('venkat')
    

    //above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}

    if you don't want to instantiate this function and call at same time.we can also do like below..

    var Person = {
      init: function(name){
        this.name=name;
      },
      print: function(){
        console.log(this.name);
      }
    };
    var obj=Object.create(Person);
    obj.init('venkat');
    obj.print();
    

    in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.

提交回复
热议问题