http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/
在js里,对象是一组键值对(在ruby,称之为hash,在python,称之为字典)。在js,key是字符串。在js立创建一个对象,语法如下:
var person = Object.create(null)
那么,为什么不直接用var person = {};
取一个键值有两种方式,person['name'],或者persion.name。
给object增加一个属性,方式如下:
-----------------------------
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");
-----------------------------
如果用prototype,可以比这更简洁。js的对象,有一个额外的属性:一个指针,指向另外一个对象,这个指针被称之为prototype。如果,在一个对象里寻找某个key,但没有找到,js会在prototype里接着找,然后以此类推进行递归,直到prototype成为null为止。
下面的例子,就是先创建第一个对象,然后,再以第一个对象为原型,创建第二个对象,然后再以第二个对象为原型,创建第三个对象。第三个对象,可以使用在第一个对象里定义的函数。
-----------------
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"
-----------------
下面两种定义方式是等价的:
------------------
var person = { firstName: "Paul", lastName: "Irish" }
------------------
等价于:
------------------
var person = Object.create(Object.prototype);
person.firstName = "Paul";
person.lastName = "Irish";
------------------
以面向对象的方式,实现一个object,是这样的:
----------------------
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype = {
toString: function() { return this.firstName + ' ' + this.lastName; }
}
----------------------
第一条语句,定义Person对象的是一个匿名函数,也是构造函数,同时也是一个object,第二条语句,是修改了Person的prototype,使之成为一段语句,这个语句里可以做很多事情。
就本质而言,一个js的class类,其实就是一个Function object函数对象,这个函数对象是构造函数和一个附加的prototype对象。