javaScript之物件

月亮販售快樂發表於2020-11-28

物件

Javascript 是一種基於物件的語言,幾乎所有東西都是物件;
物件:具體的某個事物;(如:小陳、橘貓)

1、物件建立方法:

字面量建立

let obj1 = {
    name:"小陳",
    age:"20",
    hobby:function(){
        console.log("喜歡籃球");
    }
}
 console.log(obj1);

new Object()建立:建構函式

let obj2 = new Object();
    obj2.name = "小陳";
    obj2.age = 20;
    obj2.hobby = function(){
        console.log("喜歡美女");
 }
console.log(obj2);

Object.create()建立:建立物件的原型;

 let obj3 = Object.create({
        name:"小陳",
        age:"20",
        hobby:function(){
            console.log("喜歡美女");
        }
   })
console.log(obj3);

2、物件的呼叫

console.log(obj1.name);
obj1.hobby();

3、物件賦值

let str = "name";
console.log(obj1.str);     //undefine
console.log(obj1[str]);	   //張三
let str1 = 'name';
    let obj4 = {
        [str1]:"小陳",
        age:"20",
        hobby:function(){
            console.log("喜歡美女");
        }
 }
 console.log(obj['name']);   //小陳

相關文章