[英]JavaScript objects and literal notation
我只是對JavaScript對象清除了想法,對於這里的大多數人來說,我的問題確實很簡單。 我對JavaScript對象文字表示法感到滿意,例如:
var Obj = {
/**
* @type {string}
*/
name: '',
/**
* setName
* Set the `name` property.
*
* @param param
*/
set setName (param) {
this.name = param;
}
};
我發現的唯一限制是,如果我想在同一頁面中創建兩個完全獨立的對象,則無法使用此符號。
var a = Obj;
a.setName = "John";
var b = Obj;
b.setName = "Peter";
// OUTPUT
// a.name -> Peter
// b.name -> Peter
設置var whatever = Obj
都是無用的,因為它不會實例化n
單獨的對象,並且只會覆蓋上面的代碼。 使用諸如var a = new Obj
類的new
關鍵字也不起作用(可能是我以錯誤的方式使用了它?)。 我想出的解決方案是在函數內返回對象,例如:
function Obj() {
return {
/**
* @type {string}
*/
name: '',
/**
* setName
* Set the `name` property.
*
* @param param
*/
set setName (param) {
this.name = param;
}
}
}
這樣,我可以創建兩個不同的對象並正確訪問它們的屬性和方法:
var a = Obj();
a.setName = "John";
var b = Obj();
b.setName = "Peter";
// OUTPUT
// a.name -> John
// b.name -> Peter
所以,我的問題是:
您返回一個Object
實例的函數的概念是有效的,但是您的實現非常脆弱,因為它只能設置為與特定屬性一起使用。 請繼續閱讀以獲取有關創建實例的各種方式以及返回對象的更靈活方式的更多詳細信息。
var a = Obj;
不會創建新對象。 它只是為現有對象Obj
分配a
內存地址。
var myObj = {}; // Object instance is created and memory location is stored in myObj var a = myObj; // No new object is created. a and myObj point to the same object console.log("Are 'a' and 'myObj' both pointing to the same object?", a === myObj); // true
如果要設計單個對象,然后再使用該對象,則需要能夠創建對象的“實例”。 您不能直接使用對象文字來做到這一點:
var myObj = { someProp:10 }; var myNewObj = new myObj(); // Fails because an object literal can't be instantiated
但是,您可以使用Object.create()
方法來實現 , 該方法將Obj
概念變為現實 :
// Object instance is created and memory location is stored in myObj var myObj = { someProp: "default", // "Methods" are just properties with functions as their value someMethod: function(input){ // The || syntax that follows allows for a default value for the method // if no argument is passed to the method. this.name = input || "default"; } }; // Create a new Object instance and set myObj as the prototype of the instance. // This means that the new instance will inherit from that prototype: var a = Object.create(myObj); console.log(a.someProp); // "default"; a.someProp = "something specific"; a.someMethod("Test"); myObj.someMethod(); console.log(a.name, myObj.name); // "Test" "default" console.log(a.someProp, myObj.someProp); // "something specific", "default"
可以使用new
運算符和構造函數顯式創建實例:
function foo(){ this.someProp = "something"; } var a = new foo(); // Unique instance of foo var b = new foo(); // Separate and distinct instance of foo a.someProp = 10; b.someProp = 20; console.log(a.someProp, b.someProp); // 10 20
或者, new
運算符和一個類 :
class foo{ constructor(val) { this.someProp = val; } } var a = new foo(10); // Unique instance of foo var b = new foo(20); // Separate and distinct instance of foo console.log(a.someProp, b.someProp); // 10 20
您是否嘗試過Object.create() ?
var b = { setName : "Mongo" }; a = Object.create(b); a.setName = "John"; b.setName = "Peter"; console.log(a.setName); console.log(b.setName);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.