咱们为何要使用构造函数?html
1:普通的字面量方式和new Object建立的对象方式一次只能建立一个对象,而里面的ide
属性和方法大可能是重复使用的。当咱们想建立多个相同属性和方法的对象并重复使用,就须要使用构造函数来建立。函数
2:构造函数和普通函数不同,里面封装的是一个对象。this
构造函数的语法格式:htm
function 构造函数名(){对象
this.属性名 = 值;blog
this.方法名 = function() {get
}it
}io
new 构造函数名();
实例:
function Person(uname,age,sex){
this.name = uname;
this.age = age;
this.sex = sex;
this.sing = function(sang){
console.log(sing);
}
}
var tony = new Person(‘托尼’,24,‘男’);
console.log(tony.name);
console.log(tony[‘age’]);
console.log(tony.sex);
tony.sing(‘唱歌’);
var make = new Person(‘马克’,25,‘男’);
console.log(tony.name);
console.log(tony[‘age’]);
console.log(tony.sex);
make.sing(‘周杰伦的歌’);
构造函数知识要点
1.构造函数名首字母要大写
2.构造函数不须要return,就能够返回结果
3.调用构造函数必须使用new
4.构造函数方法和属性前面要加this(构造函数的this指向建立的实例对象new)