Blogger Information
Blog 34
fans 0
comment 1
visits 23374
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0911作业:js基础语法
Samoye
Original
650 people have browsed it

编程: 创建对象的方式(字面量或构造函数)

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js中创建对象的方法</title>
    <script>
        //1. 直接创建对象 ,字面量
       let obj1 = { name: 'jimmy', sex:'female',age:18,address:'西安'};
       //测试
       document.write(obj1.name,obj1.sex,obj1.age,obj1.address);
       // 2.利用 Object 创建对象实例
        let obj2 = new Object();
        obj2.name = 'jimmy';
        obj2.sex = 'female';
        obj2.age = 18;
        obj2.address = 'BeiJing';
        //测试
        alert(obj2.address);
        //3.利用工厂模式函数创建,可以创建多个类似对象
          function createStu(name,age) {
              let obj3 = new Object();
              obj3.name = name;
              obj3.age = age;
              return obj3;
          }
          let student1 = new createStu('core',21);
          console.log(student1.name +':'+ student1.age);
        //4.用构造函数+原型对象模式 创建对象
            function Student(name,age) { //构造函数的名字,应首字母大写,以区别普通函数
                this.name=name;
                this.age=age;
                this.friends= ['jimmy','peter'];
            }
            //把方法写入proto
            Student.prototype ={
                sayName:function () {
                return this.name;
        }
            };
            let student2 = new Student('core',30);
            student2.friends.push('zola');
            console.log(student2.friends);
            console.log(student2.sayName());
    </script>
</head>
<body>

</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post