天天看點

js對象中屬性綁定和new this

<!DOCTYPE html>
<html>
<head >
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>
//------------------------自定義對象--------------------------
                //需求:單個自定義對象。
                //缺點:傳單單個對象的時候還好,建立多個多線的時候變得非常繁瑣
                //建立多個對象,for循環不能修改名字的值。函數也可以建立多個對象。
                var student = new Object();
                //    console.log(student);
                student.name = "張三";
                //    student.age = 18;
                //    student.address = "遼甯省鐵嶺市蓮花鄉池水溝子";
                student.sayHi = function () {
                    console.log(this.name+"說:大家好!");
                }
                console.log(student.name);
                student.sayHi();




//-----------------------自定義多個對象----------------------
                //需求:多個自定義對象。
                //缺點:代碼備援,方式比較low。當我們建立空白對象的時候:new Object();
                //利用構造函數自定義對象。
                var stu1 = createSudent("張三");
                var stu2 = createSudent("李四");
                console.log(stu1);
                stu1.sayHi();
                console.log(stu2);
                stu2.sayHi();
                //建立一個函數
                function createSudent(name){
                    var student = new Object();
                    student.name = name;
                    student.sayHi = function () {
                        console.log(this.name+"說:大家好!");
                    }
                    return student;
                }

//-----------------------new和this-----------------------
                //this
                //    一、this隻出現在函數中。
                //    二、誰調用函數,this就指的是誰。
                //    三、new People();   People中的this代指被建立的對象執行個體。

                //    var aaa = new Object();
                //new
                //1.開辟記憶體空間,存儲新建立的對象( new Object() )
                //2.把this設定為目前對象
                //3.執行内部代碼,設定對象屬性和方法
                //4.傳回新建立的對象

                var aaa = new stu();
                console.log(aaa);
                aaa.say();

                function stu(){
                    this.say = function () {
                        console.log(this);
                    }
                }



//-------------------------屬性綁定---------------------------

                var stu = new Object();
                var aaa = "age";

                //對象名.屬性
                stu.name = "拴柱";請求輕求保溫
                //    stu.aaa = 19;
                //對象名[變量]   對象名[值]
                stu[aaa] = 20;
                stu[0] = "你好";
                console.log(stu);

                //    var arr = [1,2,3];
                //    arr[0] = 4;


</script>
</body>
</html>
           
js