[bigdata-122] js的prototype


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对象。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值