var person={};//空對象 var person={//將成員信息寫到{}中,並賦值給一個person變量,此時person變量就是一個對象 name:"離歌", age:"20", say:function(){ console.log("你好!"); } }
咱們還能夠給對象動態添加成員信息javascript
①對象[成員名稱]=值;或 ②對象.成員名稱=值;java
本人比較推薦①這種方式,假如對象中含有「first-name」這種帶有「-」連字符的屬性時,②這種方式就會出現問題函數
獲取對象的成員信息this
①對象[成員名稱] 或 ②對象.成員名稱 //推薦方式①,理由如上spa
與工廠模式相比prototype
//方法: 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>
//方法: 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>
//方法: 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();//我具有說話的能力----
//方法: 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();//我是一個會說話的人---
//方法: 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();//我具有這項能力-----