Home > Article > Web Front-end > Why js needs constructor
Use constructors to construct reusable objects
Function in JS can be a constructor Functions can be called as ordinary functions. When new is used to create an object, the corresponding function is the constructor. When called through an object, it is an ordinary function.
The constructor is a function you construct. It is a special method that is qualitatively different from ordinary functions. Its function is mainly used to initialize the object when creating an object, which is to give the object When assigning initial values to members, the main characteristics of the constructor are the method name, the first letter is capitalized, and it is used with new
If your object has many instances, or involves inheritance or constructor parameter passing, pay attention Code comments
//创建了一个构造函数 function Person(name,address){ this.name = name; this.address = address; } //为构造函数的原型对象添加一个方法sayHello Person.prototype.sayHello = function(){ console.log('Hi I am ' + this.name); } //通过构造函数Person实例化一个p1,并传参 var p1 = new Person('postbird','earth'); //通过构造函数Person实例化一个p2,并传参 var p2 = new Person('ptbird','month'); console.log(p1);//{name: "postbird", address: "earth"} console.log(p2);//{name: "ptbird", address: "month"} // p1和p2 继承了Person的sayHello方法 p1.sayHello()//Hi I am ptbird p2.sayHello()//Hi I am postbird
Be patient and taste the above code, this will have better scalability, you can create N instances and achieve code reuse
The above is the detailed content of Why js needs constructor. For more information, please follow other related articles on the PHP Chinese website!