我刚刚清楚了解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
个单独的对象,它只是覆盖上面的代码。使用new
这样的var a = new Obj
关键字既不起作用(可能我是以错误的方式使用它?)。我想出的解决方案是将对象返回到函数中,例如:
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
所以,我的问题是:
答案 0 :(得分:4)
您返回Object
实例的函数的概念是有效的,但您的实现非常脆弱,因为它仅设置为使用特定属性。继续阅读有关创建实例的各种方法的更多详细信息以及更灵活的返回对象的方法......
var a = Obj;
无法创建新对象。它只是为a
指定现有对象Obj
的内存地址。
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
operator 和构造函数明确地创建实例:
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 :
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

答案 1 :(得分:1)
您是否尝试过使用Object.create()?
var b = { setName : "Mongo" };
a = Object.create(b);
a.setName = "John";
b.setName = "Peter";
console.log(a.setName);
console.log(b.setName);