js面向对象-1.创建多个对象(类)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21719315/article/details/82495965

我们知道通过对象直接量和Object()构造函数可以创建单个对象,当我们需要创建多个同类型的对象时,如果使用这种方法将造成大量的代码冗余。以下面为例,如果需要创建1000个点,将出现大量重复代码。

var point1={
    x:1929.100,
    y:10023.23
}

var point2={
    x:19239.100,
    y:102323.23
}

var point3={
    x:1939.100,
    y:102323.21
}

于是,开发者开始使用其他方法来改进:工厂模式、构造函数模式、原型模式。下面依次讲解:

工厂模式

由于js无法创建类(此为es5),开发人员运用工厂设计模式,直接通过函数来创建对象。

相当于,通过一个函数封装创建特定类型对象的代码。每次创建对象时,调用该函数即可。

function createStudent(school,major,name){
    var student=new Object();
    student.school=school;
    student.major=major;
    student.name=name;
    student.sayName = function(){
        alert(this.name);
    };
    return student;
}


var student2=createStudent("清华大学","软件工程","张三");
var student2=createStudent("清华大学","会计","李四");

缺点:

1. 没有解决对象的识别问题。(即该对象为何种类型?)

 

构造函数模式

通过构造函数的原理学习,我们知道当通过new调用构造函数时,将会创建一个新的对象,并赋值给this对象。此时我们就可以通过this来初始化对象的属性,当无返回值时,该新对象将会作为构造函数的返回值。

function Student(school,major,name){
    this.school=school;
    this.major=major;
    this.name=name;
    this.sayName = function(){
        alert(this.name);
    };   
}


var student2=new Student("清华大学","软件工程","张三");
var student2=new Student("清华大学","会计","李四");

如何解决工厂模式的问题?

在上例中,student1和student2都保存着Student类型的实例。这两个对象都有一个constructor属性,指向Person。

alert(studcent1.constructor == Student); //true
alert(student2.constructor == Person); //true

alert(student1 instanceof Object); //true
alert(student1 instanceof Student); //true
alert(student2 instanceof Object); //true
alert(student2 instanceof Student); //true

缺点:

1.每个方法,都需要在实例上重新创建一遍。(例如,示例中的sayName()方法)而且方法也是对象,这样重复创建多个对象,将浪费内存,影响性能。

原型模式

function Student(school,major,name,age){
    this.school=school;
    this.school=major;
    this.name=name;
    this.age=age;
}

Student.prototype.sayName=function(){
    alert(this.name);
}

var student2=new Student("清华大学","软件工程","张三");
var student2=new Student("清华大学","会计","李四");



//简写方式
function Student(school,major,name,age){
    this.school=school;
    this.school=major;
    this.name=name;
    this.age=age;
}

Student.prototype={
    sayName:function(){
        alert(this.name);
    }
}

Student.prototype.constructor=Student;


ES6

class Student(){
    constructor(school,major,name,age){
        this.school=school;
        this.major=major;
        this.name=name;
        this.age=age;
        
    }
    sayName=function(){alert(this.name);}
}

参考:

+ JavaScript高级程序设计 6.创建对象

http://es6.ruanyifeng.com/#docs/class

猜你喜欢

转载自blog.csdn.net/qq_21719315/article/details/82495965