1. 程式人生 > >js學習筆記-引用型別-object

js學習筆記-引用型別-object

//建立引用型別的兩種方式

		//1.new object()與var obj={}等同
		/*var obj = new Object();
		//或
		//var obj={};
		obj.name = "wlz";
		obj.age = 17;
		obj.eat = function() {
			console.log("我要吃飯啦!");
		}*/

		//2、物件字面法表示
		/*var obj2 = {
				name: "zs",
				age: 17,
				eat: function() {
					console.log("我要吃麵!");
				}
			}*/
			//屬性名可以加引號也可以不加
		/*var obj2 = {
			"name": "zs",
			"age": 17,
			“eat ":function(){
			console.log("我要吃麵!");
		}
		}*/
		/*console.log(obj.name);
		obj.eat()
		console.log(obj2.name);
		obj2.eat()*/
		
		//字面量建立引用型別更受青睞
		function  display(arg){
			var con="";
			if(typeof arg.name=="string"){//檢驗\一個屬性是否存在
				con+="name"+arg.name+"\n";
			}
			//訪問物件屬性:obj.name或則obj["name"]
			if(typeof arg.age=="number"){
				con+="age"+arg.age+"\n";
			}
			return con;
		}
		//console.log(typeof z);//undefined
		var obj={name:"wlz",age:17};
		console.log(obj["name"]);//另一種取屬性值表示法
		console.log(display(obj));
		console.log(display({"name":"zs"}));