面向对象理论基础(抽象、封装、继承、多态)、使用JavaScript创建对象的多种方式(关键词:类、构造函数、实例)

前言

介绍了面向对象编程(OOP)理论的基本观点,然后探讨了JavaScript如何通过构造函数来仿真对象类,以及 如何创建对象实例。

面向对象理论基础

Objects can contain related data and code, which represent information about the thing you are trying to model, and functionality or behavior that you want it to have. Object data (and often, functions too) can be stored neatly (the official word is encapsulated) inside an object package (which can be given a specific name to refer to, which is sometimes called a namespace), making it easy to structure and access; objects are also commonly used as data stores that can be easily sent across the network.

定义对象模板

    //创建模板
    const person = {

        /*
        可以使用两种方式创建name,如果使用对象的方式创建,则继续使用点号访问属性值(person.name.first),如果使用数组,则使用索引访问(person.name[0]);
         */
        name: {
            first: 'Bob',
            last: 'Smith'
        },

        // name: ['Bob', 'Smith'],


        age: 32,
        gender: 'male',
        interests: ['music', 'skiing'],
        bio: function () {
            alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. he likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');

        },

        greeting: function () {
            alert('Hi! I\' ' + this.name[0] + '.');
        }

    };

让我们考虑一个简单的程序,该程序显示有关学校中学生和老师的信息。 在这里,我们将大致看待OOP理论,而不是在任何特定的编程语言的上下文中。

关于一个人,你可以知道很多事情(地址、身高、鞋码、DNA档案、护照号码、重要的性格特征……),但在这种情况下,我们只想显示他们的姓名、年龄、性别和兴趣爱好,我们还希望能够根据这些数据写一篇简短的介绍,让他们打个招呼。这被称为抽象——为更复杂的事物创建一个简单的模型

创建实际对象

从我们的类中,我们可以创建对象实例-包含类中定义的数据和功能的对象。 从Person类中,我们现在可以创建一些实际的人:

从类创建对象实例时,将运行该类的构造函数来创建它。 从类创建对象实例的过程称为实例化-从类实例化对象实例。

When an object instance is created from a class, the class’s constructor function is run to create it. This process of creating an object instance from a class is called instantiation — the object instance is instantiated from the class.

特殊的对象-继承

在这种情况下,我们不想要person,而是想要teacher老师和student学生,他们都是更具体的人。 在OOP中,我们可以基于其他类创建新类-可以使这些新的子类(也称为子类)继承其父类的数据和代码功能

so you can reuse functionality common to all the object types rather than having to duplicate it. Where functionality differs between classes, you can define specialized features directly on them as needed.

可以使用对所有其他对象开放的公共功能,我们自己不需要复制他(打个比方,我们普通老百姓不需要自己开一个发电厂,我们直接使用国家电厂的电,我们所有老百姓都是使用国家的电,而不是自己发电,这里的电厂功能就是老百姓继承国家的,普通家庭之间除了都用电之外,有的家庭富裕一点有游泳池,有的穷一点没有游泳池,有的穷人家自己养了牛,有的有钱人家有跑车,不同的家庭拥有的不同的东西可以根据各自不同的家庭各自自己去定义)

这真的很有用-老师和学生拥有许多共同的特征,例如姓名,性别和年龄,因此只需要一次定义这些特征就很方便

多态性

您还可以在不同的类中分别定义相同的功能,因为该功能的每个定义将位于不同的名称空间中。 例如,学生的问候语可能采用“ Yo,I'm [firstName]”的形式(例如,Yo,我是Sam),而老师可能使用更正式的形式,例如“ Hello,我的名字是[Prefix ] [lastName],我教[Subject]。” (例如,您好,我叫格里菲斯先生,我在教化学)。

multiple object types to implement the same functionality is polymorphism!!!

在本文的其余部分,我们将开始研究如何在JavaScript中将OOP理论付诸实践。

构造函数和对象实例

JavaScript uses special functions called constructor functions to define and initialize objects and their features. They are useful because you’ll often come across situations in which you don’t know how many objects you will be creating; constructors provide the means to create as many objects as you need in an effective way, attaching data and functions to them as required.

让我们探索通过构造函数创建模板类,并在JavaScript中使用构造函数创建对象实例

简单构造函数案例

让我们从如何定义具有正常功能的人person开始。 在script元素中添加以下功能:

//创建对象的函数,参数是对象的参数,最后返回对象
    function createNewPerson(name) {
        const obj = {};
        obj.name = name;
        obj.greeting = function () {
            alert('Hi I\'m' + obj.name + '.');
        };
        return obj;

    }

现在,您可以通过调用此函数来创建新成员-在浏览器的JavaScript控制台中尝试以下几行:

//创建对象并分配给常量salva
const salva=createNewPerson('Salva');

这足够好,但是有点长。 如果知道要创建一个对象,为什么我们需要显式创建一个新的空对象并返回它? 幸运的是,JavaScript以构造函数的形式为我们提供了方便的快捷方式-现在让我们开始吧!

构造函数:
Replace your previous function with the following:

function Person(name) {
  this.name = name;
  this.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
}

构造函数就是是JavaScript版本的类

在构造函数中使用的this关键字-它基本上是说,每当创建某一个对象实例时,该对象的name属性将等于传递给构造函数调用的name值,greeting()方法也将使用传递给构造函数调用的name值。

根据构造函数创建对象:

    let person1 = new Person("zhandonghong");
    let person2 = new Person("vae");

现在您可以看到页面上有两个新对象,每个对象存储在不同的命名空间下-当您访问它们的属性和方法时,必须以person1或person2开始调用,

Note that when we are calling our constructor function(Person), we are defining greeting() every time, which isn’t ideal. To avoid this, we can define functions on the prototype instead, which we will look at later.

注意:构造函数的名称通常以大写字母开头-此约定用于使构造函数更易于在代码中识别。

创建完整的构造函数

我们上面看过的示例只是一个入门的简单示例。 现在开始创建最终的Person()构造函数。

删除您到目前为止插入的代码,并添加下面的替换构造函数—这在原理上与简单示例完全相同,只是稍微复杂一点:


    //定义构造函数
    function Person(first, last, age, gender, interests) {
        this.name =
            {
                first: first,
                last: last
            };
        this.age = age;
        this.gender = gender;
        this.interests = interests;
        this.bio = function () {

            let habits = '';

            for (let num = 0; num < this.interests.length; num++)
                if (num == this.interests.length - 1) {
                    habits += ' and ' + interests[num];
                } else {
                    habits += interests[num] + ',';
                }

            if (this.gender == 'male') {
                alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + habits);
            } else {
                alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. She likes ' + habits);
            }

        };
        this.greeting = function () {
            alert("Hi! I\'m " + this.name.first + '.');
        };
    }

    //    使用构造函数创建对象
    let person1 = new Person('Bob', 'Smith', 32, 'female', ['music', 'skiing', 'reading', 'fucking', 'eating']);

其他创建对象的方法

到目前为止,我们已经看到了创建对象实例的两种不同方法-声明对象字面量和使用构造函数

还有其他方法创建对象

使用Object()构造函数创建对象

First of all, you can use the Object() constructor to create a new object. Yes, even generic objects have a constructor, which generates an empty object.

创建一个空对象

let person2=new Object();

这会将一个空对象存储在person2变量中。 然后,您可以根据需要使用点或括号表示法向该对象添加属性和方法。 在控制台中尝试以下示例:

person2.name='Chris';
"Chris"
person2['age']=25;
25
person2.greeting=function(){alert('Hi I\'m '+this.name+'.');};
ƒ (){alert('Hi I\'m '+this.name+'.');}

您还可以直接将对象字面量作为参数传递给Object()构造函数:

    let personNobody={
        name:"zhandonghong",
        age:25,
        greeting:function(){
            alert('Hi I\'m '+this.name+'.');
        }
    };

    let person3=new Object(personNobody);

使用Object对象的create方法创建对象

构造函数可以帮助您确定代码的顺序-您可以先在一处创建好构造函数,然后根据需要创建实例,并且很清楚实例对象它们是来自何处。

However, some people prefer to create object instances without first creating constructors, especially if they are creating only a few instances of an object.JavaScript has a built-in method called create() that allows you to do that. With it, you can create a new object, using an existing object as the prototype of the newly created object.

把你准备好的对象实例作为参数传递给create方法

let personmax=Object.create(person1);

You’ll see that personmaxhas been created based on person1 as its prototype —it has the same properties and method available to it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值