Object解读this
Object中的create方法的第一个参数是待建立对象的原型对象,第二个参数是待建立对象的属性定义。 **属性定义解读以下:** 其中第二个参数是可选的,若是被指定了且不是undefined类型, 一个对象的可枚举的自身的属性(并不是原型链上的可枚举属性) 指定的属性描述符将会被添加到新建立的对象,和指定的属性名称同样, 这个参数的形式和使用Object.defineProperties()方法的的第二个参数是一致的。 返回值: 一个以第一个参数为原型对象且含有第二个参数指定的属性的新建立的对象 异常:当第二个参数不是空或者或者是一个普通对象;
示例spa
//shape -super class function Shape(){ this.x=0; this.y=0; }; //super class method Shape.prototype.move=function(x,y){ this.x+=x; this.y+=y; console.info('shape moved....'); }; //Rectangle -sub class function Rectangle(){ Shape.call(this);//使用对象冒充实现继承 }; //sub class extends super class Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle(); console.log('Is rect an instance of Rectangle?',rect instanceof Rectangle); //will output true console.log('Is rect an instance of Shape?',rect instanceof Shape);// will output true rect.move(1,1);// will output 'shape moved....'
Object.create的使用范例:prototype
//原型对象 var proto = { init:function(){ console.info('init method...'); }, service:function(){ console.info('service method'); }, destroy:function(){ console.info('destroy method..'); } } //目标对象 var target = Object.create(proto,{ k_init:{ value:function(){ console.info('k_init method...'); } }, k_service:{ value:function(){ console.info('k_service method...'); } }, k_destroy:{ value:function(){ console.info('k_destroy method...'); } } });
console.info(target)--->输入以下:code
console.info(Object.getPrototypeOf(target))--->输出以下:对象
未完待续...继承