什么是构造函数?
构造函数 ,是一种特殊的方法。用于在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中。
如下:Person就是一个构造函数,而new Person 就是利用构造函数实例化 一个 ws 对象
var Person = function(name,age){
this.name = name;
this.age = age;
}
var ws = new Person('王珅',5) //实例化一个ws对象
什么是构造函数的成员?
构造函数中的属性和方法就是构造函数的成员
如下例:name ,age 为Person 的属性,eat()为方法 ,都为此构造函数的成员
var Person = function(name,age){
this.name = name;
this.age = age;
this.eat = function(){
console.log("吃饭")
}
}
构造函数的成员分为:实例成员和静态成员
1.实例成员
定义:通过this添加的成员
var Person = function(name,age){
this.name = name; //实例成员
this.age = age; //实例成员
this.eat = function(){ //实例成员
console.log("吃饭")
}
}
实例成员特点:只能通过实例化对象访问,不能通过构造函数访问; 如下例
var Person = function(uname,age){
this.uname = uname;
this.age = age;
}
var ws = new Person("王珅",15)
console.log(ws.age) // 15
console.log(Person.age) // undefined
2.静态成员
定义:构造函数本身添加的成员。如下例:Person.sex , sex 即为静态成员
var Person = function(name,age){
this.name = name; //实例成员
this.age = age; //实例成员
this.eat = function(){ //实例成员
console.log("吃饭")
}
}
Person.sex = '男’;
实例成员特点:只能通过构造函数访问,不能通过实例化对象访问; 如下例
var Person = function(uname,age){
this.uname = uname;
this.age = age;
}
var ws = new Person("王珅",15)
Person.sex = '男’;
console.log(ws.sex) // undefined
console.log(Person.sex) // 男