JS创建对象的四种方式

以创建教师,学生对象为例

1,普通方式

优点:简单,方便

缺点:无法量产

var student1={
    name:"张三",
    age:23,
    study:function(){
        console.log(this.name+"正在学习");
    }
}

var student2={
    name:"李四",
    age:24,
    study:function(){
        console.log(this.name+"正在学习");
    }
}

var student3={
    name:"王五",
    age:25,
    study:function(){
        console.log(this.name+"正在学习");
    }
}

2,工厂模式

优点:实现了量产

缺点:通过工厂模式创建出来的对象无法明确对应的类型

function createStudent(name,age){
    var student=new Object();
    student.name=name;
    student.age=age;
    student.study=function(){
        console.log(this.name+"正在学习");
    }
    return student;
}

function createTeacher(name,age){
    var teacher=new Object();
    teacher.name=name;
    teacher.age=age;
    teacher.teach=function(){
        console.log(this.name+"正在教学");
    }
    return teacher;
}

var s1=createStudent("学生",18);
var reault1=s1 instanceof Object;
console.log(result1);    //true
var result2=s1 instanceof student;
console.log(result2);    //student is not defined

var t1=createTeacher("教师",26);
var reault3=t1 instanceof Object;
console.log(result3);    //true
var result4=t1 instanceof teacher;
console.log(result4);    //teacher is not defined

(1)typeof 返回数据类型

        var a=123;

        console.log(typeof a);        //number

(2)instanceof 检测对应的数据类型 (是否为对应的类,实例化出来的对象)

        var arr=[1,2,3];                                        var num=123;        //var num=new Number(123);

        var result=arr instanceof Array;                var result=num instanceof Number;

        console.log(result);        //true                console.log(result);        //false        true

(3)isPrototypeOf() 原型中的方法,判断对应的对象是否为对应构造函数创建出来的

3,构造函数

优点:明确了类型

缺点:共用的方法占据内存

function Student(name,age){
    this.name=name;
    this.age=age;
    this.study=function(){
        console.log(this.name+"正在学习");
    }
}

function Teacher(name,age){
    this.name=name;
    this.age=age;
    this.teach=function(){
        console.log(this.name+"正在教学");
    }
}

var s1=new Student("学生1",18);
var s2=new Student("学生2",20);
var t1=new Teacher("教师",26);

var result1=s1 instanceof Student;
console.log(result1);    //true
var result2=t1 instanceof Teacher;
console.log(result2);    //true

console.log(s1.study==s2.study);   //false 

new 做了什么?

(1)创建了一个空对象{}

(2)执行后面的构造函数,将函数内容this指向空对象

(3)函数执行完成后,将创建的空对象返回给前方变量

4,原型模式

在创建构造函数的过程中,将共有的方法放入构造函数的原型里

function Student(name,age){
    this.name=name;
    this.age=age;
}
Student.prototype.study=function(){
    console.log(this.name+"正在学习");
}

var s1=new Student("张三",18);
var s2=new Student("李四",20);

console.log(s1.study==s2.study);    //true
console.log(s1.__proto__==s2.__proto__);    //true
console.log(s1.__proto__==Student.prototype);    //true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值