标签:function me create Object 笔记 prototype Rectangle
Object.create方法会返回一个新对象(带有指定的原型对象和属性)1. 基于一个对象去创建新的对象
1 var person = { 2 isHuman: false, 3 print: function() { 4 console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`); 5 }, 6 }; 7 8 const me = Object.create(person); 9 10 // 'name'是 me 的自有属性(非person对象的) 11 me.name = 'John'; 12 // 继承自person上的isHuman属性将被改写 13 me.isHuman = true; 14 15 me.print();
2. 实现继承
1 // 父类 - Shape 2 function Shape() { 3 this.x = 0; 4 this.y = 0; 5 } 6 7 Shape.prototype.move = function(x, y) { 8 this.x += x; 9 this.y += y; 10 }; 11 12 // 子类 - Rectangle 13 function Rectangle() { 14 Shape.call(this); 15 } 16 17 // 继承 18 Rectangle.prototype = Object.create(Shape.prototype); 19 Rectangle.prototype.constructor = Rectangle; 20 21 var rect = new Rectangle();
3. 方法使用细节
1 var o; 2 // 创建一个原型为null的空对象 3 o = Object.create(null); 4 5 // 以字面量创建的空对象 o = {} 相当于: 6 o = Object.create(Object.prototype); 7 8 // 关于Object.create的 propertyObject 参数的使用 9 o = Object.create(Object.prototype, { 10 // 添加数据属性 11 foo: { 12 writable: true, 13 configurable: true, 14 value: 'hello', 15 }, 16 // 添加存取器属性 17 bar: { 18 configurable: false, 19 get: function() { 20 return 10; 21 }, 22 set: function(val) { 23 console.log('Set "o.bar" to ', val); 24 }, 25 }, 26 }); 27 28 // function Cons() {} 29 // var c = new Cons(); 30 // // 等同于: 31 // var o = Object.create(Cons.prototype);
标签:function,me,create,Object,笔记,prototype,Rectangle 来源: https://www.cnblogs.com/fanqshun/p/15624123.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。