构造函数就是一个普通的函数,创建方式和普通函数没有区别,不同的是构造函数习惯上首字母大写。
构造函数和普通函数的区别就是调用方式的不同:普通函数是直接调用,而构造函数需要使用new关键字来调用
构造函数的执行流程:
- 创建一个新的对象
- 将新建的对象设置为函数中this ,在构造函数中可以使用this来引用新建的对象
- 逐行执行函数中的代码
- 将新建的对象作为返回值返回
使用同一个构造函数创建的对象,我们称为一类对象,也将一个构造函数称为一个类。
我们将通过一个构造函数创建的对象,称为是该类的实例
代码:
<script>
function Person(name,age,gender){
this.name=name;
this.age=age;
this.gender=gender;
this.sayName=function(){
alert(this.name);
}
}
var per1=new Person("易烊千玺",22,"男 ");
var per2=new Person("易烊千玺2",22,"男 ");
function Dog(){
}
var dog=new Dog();
console.log(per1);
console.log(dog);
</script>
使用instanceof可以检查一个对象是否是一个类的实例
语法: 对象 instanceof 构造函数
如果是,则返回true,否则返回false
console.log(per1 instanceof Person);//true
所有的对象都是Object的后代,所以任何对象和Object做instanceof检查时都会返回true
console.log(per1 instanceof Object);//true
函数共享同一个函数:
function Person(name,age,gender){
this.name=name;
this.age=age;
this.gender=gender;
this.sayName=fun;
}
function fun(){
alert(this.name);
}
var per1=new Person("易烊千玺1",22,"男 ");
var per2=new Person("易烊千玺2",22,"男 ");
per1.sayName();
per2.sayName();
console.log(per1.sayName==per2.sayName);//true