js建立對象的幾種方式

1.經過"字面量"建立

var person={};//空對象

var person={//將成員信息寫到{}中,並賦值給一個person變量,此時person變量就是一個對象
    name:"離歌",
    age:"20",
    say:function(){
       console.log("你好!");
    }
}

咱們還能夠給對象動態添加成員信息javascript

①對象[成員名稱]=值;或 ②對象.成員名稱=值;java

本人比較推薦①這種方式,假如對象中含有「first-name」這種帶有「-」連字符的屬性時,②這種方式就會出現問題函數

獲取對象的成員信息this

①對象[成員名稱] 或 ②對象.成員名稱  //推薦方式①,理由如上spa

2.經過"構造函數"建立

與工廠模式相比prototype

  • 無需在函數內建立對象,而是用this代替
  • 無需明確return返回值
//方法:
var 變量名=new 函數名();
//例子:
var person=new Person();//構造函數

經過該方法建立對象時,會自動執行該函數code

<script>
	$(document).ready(function(){
		function Person(){
			this.name="www";
			this.age="20";
			this.say=function(){
				console.log("擁有會說話的技能");
			}
			console.log("我是一我的----");
		}
		var person=new Person();//輸出我是一我的----
	});
</script>

3.經過object方式建立

//方法:
var 變量名=new Object();
//例子:
var person=new Object();//經過object方式建立
<script>
	$(document).ready(function(){
		var person=new Object();
		person.name="李四";
		person.age="20";
		person.say=function(){
			console.log("我擁有說話的行爲------");
		};
		person.say();//輸出我擁有說話的行爲------
	});
</script>

4.工廠模式

  • 在函數中定義對象,並定義對象的各類屬性(包括屬性和方法)
  • 引用對象的時候用的是=函數名()而不是=new 函數名()
  • 在函數的最後返回對象
//方法:
function 函數名(){
   var child=new Object();
   return child;
}
var 變量=函數名();
//例子:
function Person(){
   var child=new Object();
   child.name="李四";
   child.age="20";
   child.say=function(){
     console.log("我具有說話的能力----");
}
   return child;
}
var person=Person();
person.say();//我具有說話的能力----

把上面例子重構下對象

//把方法屬性提取出來,爲了不重複建立該方法
function say(){
   console.log("我具有說話的能力----");
}
function Person(){
   var child=new Object();
   child.name="李四";
   child.age="20";
   child.say=say;
   return child;
}
var person=Person();
person.say();//我具有說話的能力----

5.原型模式

  • 只建立一個空函數,裏面不聽任何內容
  • 利用prototype屬性,對函數的屬性進行綁定
  • 調用的時候new 函數名
//方法:
function 函數名(){

}
函數名.prototype.name="李四";
函數名.prototype.age="20";
函數名.prototype.say=function(){
   console.log("我是一個會說話的人---");
}
var person=new 函數名();
//例子:
function Person(){

}
Person.prototype.name="李四";
Person.prototype.age="20";
Person.say=function(){
     console.log("我是一個會說話的人---");
}
var person=new Person();
person.say();//我是一個會說話的人---

6.混搭(原型模式+構造函數)

  • 函數中定義屬性
  • 函數外結合prototype屬性定義方法
  • 調用時使用new 函數名()
//方法:
function 函數名(){
   this.name="李四";
   this.age="20";
}
函數名.prototype.say=function(){
    console.log("我具有這項能力-----");
}
var person=new 函數名();
person.say();
//例子:
function Person(){
   this.name="李四";
   this.age="20";
}
Person.prototype.say=function(){
    console.log("我具有這項能力-----");
}
var person=new Person();
person.say();//我具有這項能力-----
相關文章
相關標籤/搜索