正确的方法来创建对象

时间:2012-02-10 17:32:54

标签: javascript object coding-style

创建对象(具有“名称空间”等)的正确方法是什么?

1

//Company object
var Microsoft = {};

//Create an employee
Microsoft.employee = function(name) {
   this.name = name;
}

2

//Company object
Apple = {

   employee: function(name) {
      this.name = name;
   }

}

另一种方式?拍摄。

阅读有关原型等的内容。什么是正确的方法;好处和缺点?

1 个答案:

答案 0 :(得分:4)

首先,您忘记了var Apple。但除此之外基本上都是一样的。

其次,在我的示例中,我不打算使用属性name,因为在处理函数时,name默认为空字符串。至少在Node.js和Chrome中。所以我会改用empName

Microsoft示例中,您正在制作一个空对象,然后在事后添加一个属性。

Apple示例中,您正在创建一个具有该属性的对象。

这真的只是对你最有意义的,也是你喜欢的。因为它们或多或少是等价的。

现在,这与原型无关。以下是您所做的一个示例:

var Apple = { 
    employee: function(empName) {
        this.empName = empName;
    }
};

Apple.employee('Hank');
Apple.empName; // 'Hank'

以下是使用实例(使用new运算符和prototype

执行此操作的方法
var Apple = function() {}; // base 'parent'

Apple.prototype.employee = function(empName) {
    this.empName = empName
};

var a = new Apple();
a.employee('Hank');
a.empName; // 'Hank'
Apple.empName; // undefined

所以prototype用于向对象的新实例添加属性(松散地使用'object')。请注意,要访问employee中的Apple,在第二个示例中,您必须执行类似

的操作
Apple.prototype.employee('Hank'); // doesn't really do much
Apple.empName; // undefined

// but you can call the employee prototype with a bound variable
// you'd do this if you don't want to make an instance of Apple
// but still want to use one of it's prototypes
var obj = {};
Apple.prototype.employee.call(obj, 'Hank');
obj.empName; // 'Hank'

// a practical use of accessing a prototype method is
// when wanting to convert a function's arguments
// to an array. function arguments are like an array,
// but until turned into one they are not completely the same
var func = function() {
    var args = Array.prototype.slice.call(arguments);
    var sum = 0;
    for(var i = 0, l = args.length; i < l; i++) {
        sum += args[i];
    }
    return sum;
};

func(1); // 1
func(1, 2, 3, 4, 5); // 15

希望有所帮助。

编辑:另外,请不要设置原型对象(例如{}Object)。这样做并不安全。实际上,由于JavaScript中的每个变量都是一个对象,因此您添加到它们的任何原型都将在所有变量上可用。因此,如果您Object.prototype.xyz = 12然后var obj = { a: 1, b: 2, c: 3}然后尝试for(var key in obj) { console.log(key); },则会产生以下日志:abcxyz ...你不想要的。

相关问题