Object.create()
Object.create()方法创建一个新的对象,使用现有的对象来提供新创建对象的proto.
语法:
Object.create(proto, [propertiesObject])
参数:
proto:新创建对象的原型对象,
propertiesObject:可选,需要传入一个对象.该对象的属性类型,参照Object.defineProperties()的
第二个参数.如果该参数被指定且不为undefined,该传入对象的自有可枚举属性(即其自身定义的属性,而不是其原型链上的枚举属性)将为新创建的对象添加指定的属性值和对应的属性描述符.
返回值:一个新对象,带着指定的原型对象和属性
例外:如果propertiesObject参数是null或非原始包装对象,则抛出一个typeerror异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| const person = { isHuman: false, printIntroduction: function() { console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`); } }; const me = Object.create(person); console.log(me);
me.name = 'zjy'; me.isHuman = true; me.printIntroduction(); console.log(me);
var xxx = Object.create({ a:'a' },{ 'str':{ value:'zjy' }, 'name':{ value:'ha' } }); console.log(xxx);
var aObj = { a:'zjy', b:'name', c:function(n){ console.log('n:'+n); } }; var _aObj = Object.create(aObj,{ txt:{ value:'Object.create()方法的继承' } }); console.log(_aObj);
_aObj.c('haha');
|