本篇內容主要講解“JS怎么創建對象”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“JS怎么創建對象”吧!
一、new Object();
var x="age" var obj=new Object(); obj.name="wang"; obj.x=20; //.字符串 obj[x]=25; //[變量] console.log(obj);//{name: "wang", x: 20, age: 25}
二、字面量
var a="hobby" var obj={"name":"wang","age":"18"}; obj.sex="男"; obj[a]="唱歌"; obj.say=function(){ } console.log(obj);//{name: "wang", age: "18", sex: "男", hobby: "唱歌", say: ?} var obj2={"aa bb":"hellow",".x":"world"}; console.log(obj2["aa bb"]);//hellow console.log( obj2[".x"] );//world
三、工廠模式;
//1.創建函數 function a(name, age) { var obj = { "name": "wang", "age": 19, "say": function () { } } return obj } //2.依次調用 var obj1 = a("wang", 20); console.log(obj1);//{name: "wang", age: 19, say: ?} console.log(obj1 instanceof Object);//true //優點:返回新對象,互不影響 //缺點:代碼重復(方法相同)。 // 沒有從屬關系,
四、構造函數
//四、構造函數; //優點:有從屬 //缺點:代碼重復(相同方法); // 1.創建函數 //2.傳入參數 function A(name,age){ //3.this。屬性名=值 this.name=name; this.age=age; this.say=function(){ } } //調用 : var obj=new 構造函數(參數) var obj= new A("wang",19); console.log(obj); console.log( obj instanceof Object );//true console.log( obj instanceof A );//true
五、原型模式
//原型優點:共同/相同的屬性、方法不重復 有從屬關系 //缺點:原型上的屬性不可單獨改變 function Fn(){ } Fn.prototype.name="王"; Fn.prototype.age=19; var obj=new Fn(); console.log(obj); /* 修改obj.__proto__.name obj.__proto__.name 發生變化 obj2.__proto__.name 也發生變化 obj和obj1 共用__proto__對象 公共/相同的屬性、方法放在構造函數.prototype上 實現代碼不重復 */ obj.__proto__.name="李" console.log( obj.__proto__.name ); var obj2=new Fn(); console.log(obj2); console.log(obj.__proto__.name);
到此,相信大家對“JS怎么創建對象”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。