Home > Web Front-end > JS Tutorial > Why js needs constructor

Why js needs constructor

(*-*)浩
Release: 2019-06-15 17:58:09
Original
3922 people have browsed it

Use constructors to construct reusable objects

Why js needs constructor

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
Copy after login

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!

Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template