javascript - How do I add prototype-like properties to an existing object? -
i start off simple object like:
var person = { name: 'joe', age: 21 };
i want add method object without method showing when use hasownproperty. example, let's create birthday method increments person's age.
var birthday = function() { this.age++; };
how add person object if say:
for(var in person) { console.log(i); }
i get:
name: 'joe' age: 21 birthday: function() { ... }
but if say:
for(var in person) { if(person.hasownproperty(i)) { console.log(i, person[i]); } }
i get:
name: 'joe' age: 21
var person = { name: 'joe', age: 21 }; object.defineproperty(person, 'birthday', { enumerable: false, configurable: false, writable: false, value: function() { this.age++; } }); function showperson() { for(var in person) { if(person.hasownproperty(i)) { console.log(i, person[i]); } } } showperson(); person.birthday(); showperson();
if iterating methods without hasownproperty important,. following idea might work..
var person = { name: 'joe', age: 21 }; var extend = { birthday: function () { this.age ++ } } var person = object.assign( object.create(extend), person); function showperson() { for(var in person) { if(person.hasownproperty(i)) { console.log(i, person[i]); } } } function showpersonfull() { for(var in person) { console.log(i, person[i]); } } showperson(); person.birthday(); showpersonfull();
wiki
Comments
Post a Comment