2021-12-05

使用对象制作计算器


  //定义一个计算器对象

        let calc = {

            //定义计算器的属性

            num1:0,

            num2:0,

            //定义计算器的方法

            jia:function(){

                //在对象的方法中,获取对象的其它成员,要通过this

                console.log(`${this.num1}+${this.num2}=${this.num1+this.num2}`);

            },

            //在SE6中,对象的方法,也可以采用下面的方式

            jian(){

                console.log(`${this.num1}-${this.num2}=${this.num1-this.num2}`);

            },

            cheng(){

                console.log(`${this.num1}*${this.num2}=${this.num1*this.num2}`);

            },

            chu(){

                console.log(`${this.num1}/${this.num2}=${this.num1/this.num2}`);

            }

        }

        //给计算器对象的两个属性赋值

        calc.num1 = 200

        calc.num2 = 20

        calc.jia()

        calc.jian()

        calc.cheng()

        calc.chu()


构造函数

 // 构造函数:首先是个函数,这个函数用来创建出对象

 // 如果使用构造函数创建出对象:使用new关键字。

 // 可以使用系统构造函数Object创建一个对象。效果等同于{}

        let obj1 = new Object()  

        console.log(obj1);

        let obj2 = {}

        console.log(obj2);

        console.log('--------------------------------');

        // 多数情况下,都是先自定义一个构造函数,再通过自定义的构造函数创建出对应的对象

        // 可以将构造函数理解成:类

        function Student(no,name,age,sex){

            //这里的this,用于给构造函数定义成员

            this.no = no

            this.name = name

            this.age = age

            this.sex = sex

            this.sayHi = function(){

                console.log(`大家好!我叫${this.name}`);

            }

        }

        // 通过类(构造函数)可以创建出无数个对象

        let s1 = new Student(1001,'张三',20,'男')

        console.log(s1);

        s1.sayHi()

        let s2 = new Student(1002,'李四',22,'女')

        console.log(s2);

        s2.sayHi()

        let s3 = new Student(1003,'王五',24,'男')

        console.log(s3);

        s3.sayHi()


练习:

  // 定义一个棋子构造函数(类)

        function Chess(name,color,x,y){

            //定义属性

            this.name=name

            this.color=color

            this.x=x

            this.y=y

            //定义方法

            //显示当前位置的方法

            this.show=function(){

                console.log(`${this.color}${this.name},当前位置是X:${this.x} Y:${this.y}`);

            }

            //移动棋子的方法

            this.move=function(x,y){

                this.x = x

                this.y = y

                //位置更新后,重新调用显示当前位置的方法

                this.show()

            }

        }

        // 创建一个红马

        let redHorse = new Chess('马','红',15,1)

        redHorse.show()

        redHorse.move(13,2)

        //创建一个黑车

        let blackCar = new Chess('车','黑',1,1)

        blackCar.show()

        blackCar.move(5,1)

结果:

构造函数练习  运行的结果

你可能感兴趣的:(2021-12-05)