使用工厂方法创建对象,使用的构造函数都是Object,所以创建的对象都是Object这个类型,导致无法区分多种类型的对象
希望把new Object();改成=>new Person();,new newClass();
创建一个构造函数,专门用来创建person对象的,构造函数就是一个普通的函数,创建方式和普通函数没有区别,不同的是构造函数习惯上大写。
构造函数和普通函数的区别:调用方式不同
普通函数之间调用,构造函数需要使用new关键字来调用
function Person(){
}
var a=Person();//作为普通函数
console.log(a);

function Person(){
}
var a= new Person()//作为构造函数
console.log(a);
构造函数执行流程:
function Person(){
this.age=23;
this.name='张三';
}
var a= new Person()//作为构造函数
console.log(a.name);
- function Person(){
- this.age=23;
- this.name='张三';
- }
- var a= new Person()//作为构造函数
- console.log(a.name);
使用同一个构造函数创建的对象=>同一类
同一个构造函数创建的对象教=》该类的实例 ab是person的实例
- function Person(name, age, gender) {
- this.age = age;
- this.name = name;
- this.gender = gender;
- this.sayName = function() {
- console.log(this.age)
- };
- }
- var a = new Person("张三", 34, "颠倒");//作为构造函数
- var b = new Person("李四", 34, "颠倒");
- function Dog() {
-
- }
- var c = new Dog();
- console.log(c)
- console.log(a);

使用instance of检查一个对象是否是一个类的实例
语法:对像 instanceof 实例
console.log(a instanceof Person)
console.log(c instanceof Dog);
console.log(a instanceof Object)
console.log(c instanceof Object);

注意所有的对象都是Object的后代,所以任何对象的和instanceof检查时候都会返回true