很全面的JavaScript常用功能汇总集合(4)

var Person = { name: "Person", properties: { firstName: {range:"NonEmptyString", label:"First name", writable: true, enumerable: true}, lastName: {range:"NonEmptyString", label:"Last name", writable: true, enumerable: true} }, methods: { getFullName: function () { return this.firstName +" "+ this.lastName; } }, create: function (slots) { // create object var obj = Object.create( this.methods, this.properties); // add special property for *direct type* of object Object.defineProperty( obj, "type", {value: this, writable: false, enumerable: true}); // initialize object Object.keys( slots).forEach( function (prop) { if (prop in this.properties) obj[prop] = slots[prop]; }) return obj; } };

注意JS对象Person实际表示的是factory-based 类。factory-based类的实例化是通过调用它自己的Create方法实现的:

var pers1 = Person.create( {firstName:"Tom", lastName:"Smith"});
getFullName 方法是通过pers1. 调用的,如下:

alert("The full name of the person are: " + pers1.getFullName());
每个属性的声明都是使用Object.Create 声明的,其中包含三个参数及值,'descriptors'writable: true and enumerable: true;如上面第五行的。

是不是一篇很赞的文章,果断收藏吧!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwgfx.html