出于本文的目的,我将使用ECMAScript 5.1中定义的语法来讨论JavaScript对象。第3版中存在基本语义,但它们并没有很好地暴露出来。
一个全新的对象
在JavaScript中,对象是键和值对(在Ruby中,这种结构称为Hash;在Python中,它称为字典)。例如,如果我想描述我的名字,我可以有一个带有两个键的对象:firstName指向“Yehuda”并lastName指向“Katz”。JavaScript对象中的键是字符串。
要在JavaScript中创建最简单的新对象,您可以使用Object.create:
var person = Object.create(null); // this creates an empty objects
我们为什么不用它var person = {};?坚持我!要按键在对象中查找值,请使用括号表示法。如果相关密钥没有值,则JavaScript将返回undefined。
person['name'] // undefined
如果String是有效的标识符[1],您可以使用点形式:
person.name // undefined
[1]通常,标识符以unicode字母$,_开头,后跟任何起始字符或数字。有效标识符也不能是保留字。还有其他允许的字符,例如unicode组合标记,连接标点符号的unicode和unicode转义序列。查看规格了解完整详情
添加值
所以现在你有一个空对象。没那么有用,嗯?在我们添加一些属性之前,我们需要了解一个属性(规范称为“命名数据属性”)在JavaScript中是什么样的。
显然,属性具有名称和值。此外,属性可以是可枚举的,可配置的和可写的。如果值是可枚举的,则在使用for(prop in obj)循环枚举对象时将显示该值。如果属性是可写的,则可以替换它。如果属性是可配置的,您可以删除它或更改其他属性。
通常,当我们创建一个新属性时,我们希望它是可枚举的,可配置的和可写的。事实上,在ECMAScript 5之前,这是用户可以直接创建的唯一属性。
我们可以使用添加属性到对象Object.defineProperty。让我们为空对象添加名字和姓氏:
var person = Object.create(null);
Object.defineProperty(person, 'firstName', {
value: "Yehuda",
writable: true,
enumerable: true,
configurable: true
});
Object.defineProperty(person, 'lastName', {
value: "Katz",
writable: true,
enumerable: true,
configurable: true
});
显然,这非常冗长。我们可以通过消除常见的默认值来减少冗长:
var config = {
writable: true,
enumerable: true,
configurable: true
};
var defineProperty = function(obj, name, value) {
config.value = value;
Object.defineProperty(obj, name, config);
}
var person = Object.create(null);
defineProperty(person, 'firstName', "Yehuda");
defineProperty(person, 'lastName', "Katz");
尽管如此,创建一个简单的属性列表仍然非常难看。在我们找到更漂亮的解决方案之前,我们需要为JavaScript对象库添加另一种武器。
原型
到目前为止,我们已经将对象称为简单的键和值对。实际上,JavaScript对象还有一个附加属性:指向另一个对象的指针。我们将此指针称为对象的原型。如果您尝试在对象上查找某个键并且找不到它,JavaScript将在原型中查找它。它将遵循“原型链”,直到它看到一个null值。在那种情况下,它返回undefined。
你会记得我们通过调用创建了一个新对象Object.create(null)。该参数告诉JavaScript它应该设置为Object的原型。您可以使用以下命令查找对象的原型Object.getPrototypeOf:
var man = Object.create(null);
defineProperty(man, 'sex', "male");
var yehuda = Object.create(man);
defineProperty(yehuda, 'firstName', "Yehuda");
defineProperty(yehuda, 'lastName', "Katz");
yehuda.sex // "male"
yehuda.firstName // "Yehuda"
yehuda.lastName // "Katz"
Object.getPrototypeOf(yehuda) // returns the man object
我们还可以通过这种方式添加我们在多个对象中共享的函数:
var person = Object.create(null);
defineProperty(person, 'fullName', function() {
return this.firstName + ' ' + this.lastName;
});
// this time, let's make man's prototype person, so all
// men share the fullName function
var man = Object.create(person);
defineProperty(man, 'sex', "male");
var yehuda = Object.create(man);
defineProperty(yehuda, 'firstName', "Yehuda");
defineProperty(yehuda, 'lastName', "Katz");
yehuda.sex // "male"
yehuda.fullName() // "Yehuda Katz"
设置属性
由于创建一个新的可写,可配置,可枚举的属性非常常见,因此JavaScript可以使用赋值语法轻松完成。让我们使用赋值更新前面的示例,而不是defineProperty:
var person = Object.create(null);
// instead of using defineProperty and specifying writable,
// configurable, and enumerable, we can just assign the
// value directly and JavaScript will take care of the rest
person['fullName'] = function() {
return this.firstName + ' ' + this.lastName;
};
// this time, let's make man's prototype person, so all
// men share the fullName function
var man = Object.create(person);
man['sex'] = "male";
var yehuda = Object.create(man);
yehuda['firstName'] = "Yehuda";
yehuda['lastName'] = "Katz";
yehuda.sex // "male"
yehuda.fullName() // "Yehuda Katz"
就像查找属性一样,如果您定义的属性是标识符,则可以使用点语法而不是括号语法。例如,你可以man.sex = "male"在上面的例子中说。
对象文字
不过,每次必须设置多个属性会让人烦恼。JavaScript提供了一种文字语法,用于创建对象并一次为其分配属性。
var person = { firstName: "Paul", lastName: "Irish" }这个语法大概是糖:
var person = Object.create(Object.prototype);
person.firstName = "Paul";
person.lastName = "Irish";
关于扩展形式最重要的是对象文字总是将新创建的对象的原型设置为位于的对象Object.prototype。在内部,对象文字看起来像这样:

默认Object.prototype字典带有许多我们期望对象包含的方法,并且通过原型链的魔力,作为对象文字创建的所有新对象都将包含这些属性。当然,对象可以通过直接定义属性来愉快地覆盖它们。最常见的是,开发人员将覆盖该toString方法:
var alex = { firstName: "Alex", lastName: "Russell" };
alex.toString() // "[object Object]"
var brendan = {
firstName: "Brendan",
lastName: "Eich",
toString: function() { return "Brendan Eich"; }
};
brendan.toString() // "Brendan Eich"
这特别有用,因为许多内部强制操作使用提供的toString方法。
不幸的是,这种文字语法只有在我们愿意制作新对象的原型时才有效Object.prototype。这消除了我们之前看到的使用原型共享属性的好处。在许多情况下,简单对象文字的便利性超过了这种损失。在其他情况下,您将需要一种简单的方法来创建具有特定原型的新对象。我会在之后解释:
var fromPrototype = function(prototype, object) {
var newObject = Object.create(prototype);
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
newObject[prop] = object[prop];
}
}
return newObject;
};
var person = {
toString: function() {
return this.firstName + ' ' + this.lastName;
}
};
var man = fromPrototype(person, {
sex: "male"
});
var jeremy = fromPrototype(man, {
firstName: "Jeremy",
lastName: "Ashkenas"
});
jeremy.sex // "male"
jeremy.toString() // "Jeremy Ashkenas"
让我们解构这个fromPrototype方法。此方法的目标是使用一组属性创建一个新对象,但使用特定原型。首先,我们将使用Object.create()创建一个新的空对象,并分配我们指定的原型。接下来,我们将枚举我们提供的对象中的所有属性,并将它们复制到新对象。
请记住,当您创建一个对象文字时,就像我们传入的对象文字一样fromPrototype,它将始终Object.prototype作为其原型。默认情况下,JavaScript的包括在性质Object.prototype是不可枚举,所以我们不必担心valueOf显示我们的循环了。但是,由于它Object.prototype是一个像任何其他对象一样的对象,任何人都可以在其上定义一个新属性,它可能(并且可能会)被标记为可枚举。
因此,当我们循环遍历传入的对象的属性时,我们希望将复制限制为在对象本身上定义的属性,而不是在原型上找到的属性。JavaScript包含一个方法hasOwnProperty,Object.prototype用于检查是否在对象本身上定义了属性。由于对象文字将始终Object.prototype作为其原型,您可以以这种方式使用它。
我们在上面的示例中创建的对象如下所示:

原生对象方向
在这一点上,很明显原型可以用来继承功能,就像传统的面向对象语言一样。为了便于以这种方式使用它,JavaScript提供了一个new操作员。
为了促进面向对象的编程,JavaScript允许您使用Function对象作为用于新对象的原型和要调用的构造函数的组合:
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype = {
toString: function() { return this.firstName + ' ' + this.lastName; }
}
在这里,我们有一个Function对象,它既是构造函数,也是用作新对象原型的对象。让我们实现一个从这个Person对象创建新实例的函数:
function newObject(func) {
// get an Array of all the arguments except the first one
var args = Array.prototype.slice.call(arguments, 1);
// create a new object with its prototype assigned to func.prototype
var object = Object.create(func.prototype);
// invoke the constructor, passing the new object as 'this'
// and the rest of the arguments as the arguments
func.apply(object, args);
// return the new object
return object;
}
var brendan = newObject(Person, "Brendan", "Eich");
brendan.toString() // "Brendan Eich"
newJavaScript中的运算符基本上可以完成这项工作,为那些熟悉传统面向对象语言的人提供了一种熟悉的语法:
var mark = new Person("Mark", "Miller");
mark.toString() // "Mark Miller"
本质上,JavaScript“类”只是一个Function对象,用作构造函数和附加的原型对象。我之前提到的早期版本的JavaScript没有Object.create。由于它非常有用,人们经常使用new运算符创建类似的东西:
var createObject = function (o) {
// we only want the prototype part of the `new`
// behavior, so make an empty constructor
function F() {}
// set the function's `prototype` property to the
// object that we want the new object's prototype
// to be.
F.prototype = o;
// use the `new` operator. We will get a new
// object whose prototype is o, and we will
// invoke the empty function, which does nothing.
return new F();
};
我真的很喜欢ECMAScript 5和更新版本已经开始暴露实现的内部方面,比如允许您直接定义不可枚举的属性或直接使用原型链定义对象。
3221



被折叠的 条评论
为什么被折叠?



