ES6 對象的創建及操作


對象的創建方式包括 以下3種:(new Object(),new 構造函數的形式 , Object.create(properties),)

"use strict"

// 方式1

var person = new Object()

person["name"]="jimmy"

console.log(person.name)

person.age=20

console.log(person.age)

console.log(person)

 var myCar = new Object()

var propertyName = "make";

myCar[propertyName] = "Ford";

var propertyName1 = "year"

myCar[propertyName1]=1990

console.log(myCar.make)

console.log(myCar.year)

// 方式2

//構造函數

function Car(){

this.make = "Ford"

this.model = "F123"

}

var obj = new Car()

console.log(obj.make)

console.log(obj.model)

// 方式3 Object.create

var roles = {

type:"Admin",//Default value of properties

displayType:function(){

  console.log(this.type);//Mehtod which will display type of role

}

}

var super_role = Object.create(roles);

super_role.displayType();

 

var guest_role = Object.create(roles);

guest_role.type = "Guest";

guest_role.displayType();

 var testObj = Object.create(null)

testObj.type = "xx"

testObj.displayType = new Function("a","console.log(a)");

testObj.displayType("abc")

 

//object assign

var det = {name:"Tom",ID:"E1001"};

// 初始化對象並且給默認值

var copy = Object.assign({},det);

console.log(copy);

for(let val in copy){

console.log(copy[val]);

}

//

var properties = {

name: "john",

ID :"E1002",

age: 28

};

var jo = Object.create(properties);

console.log(jo.name);

console.log(jo.ID);

var john = Object.assign(properties);

console.log(john);

var john1 = Object.assign(john,det);

console.log(john1);

//合並對象,合並對象時大對象沒有做拷貝的操作,而是直接引用了對象的指針

var o1 = {a:10};

var o2 = {b:20};

var o3 = {c:30};

// 將值合並到o1 並且返回o1 , 返回值就是被合並的對象

var obj = Object.assign(o1,o2,o3);

console.log(obj);

console.log(o1);

if(o1 === obj){

console.log("o1 is the same as the obj");

}else{

console.log("o1 is different from obj");

}

// o2的值沒有改變

console.log(o2);

 var o1 = {a:10};

var obj = Object.assign(o1);

obj.a++;

console.log("Value of 'a' in the Merged object after increment");

console.log(obj.a);

console.log("Value of 'a' in the Original Object after increment");

console.log(o1.a);

 // delete properties 刪除對象中的屬性

 var myobj = new Object;

myobj.a = 5;

myobj.b = 12;

 console.log("before deleting the myobj value is :");

console.log(myobj);

delete myobj.a

console.log("after deleting the myobj value is :");

console.log(myobj);

 //比較

var val1 = {name:"Tom"};

var val2 = {name:"Tom"};

console.log(val1 == val2)//return false

console.log(val1 === val2)//return false

 

var val1 = {name:"Tom"};

var val2 = val1;

console.log(val1 == val2);

console.log(val1 === val2);

 

var emp = {name:'John',Id:3}

var {name,Id} = emp

console.log(name)

console.log(Id)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM