加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[bigdata-122] js的prototype

发布时间:2020-12-14 04:57:05 所属栏目:大数据 来源:网络整理
导读:http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/ 在js里,对象是一组键值对(在ruby,称之为hash,在python,称之为字典)。在js,key是字符串。在js立创建一个对象,语法如下: var person = Object.create(null) 那么,为什么
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",? configurable: true }); ----------------------------- 等价的,一个更简洁的方式如下: ----------------------------- var config = { ? writable: true,? configurable: true }; var defineProperty = function(obj,name,value) { ? config.value = value; ? Object.defineProperty(obj,config); } var person = Object.create(null); defineProperty(person,"Yehuda"); defineProperty(person,? "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对象。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读