On Feb 13, 5:55 pm, Douglas Crockford <nos...@sbcglobal.netwrote:
kirkox wrote:
Hi guys, this is my first post here and I am a newbie, of course.
My question is simple...I'd like to override toString() function such
that it can works on Object.
How can I override toString function?
Object.prototype.toString = function () {
return stringify(this);
};
Seehttp://yuiblog.com/blog/2006/09/26/for-in-intrigue/
I don't think it is quite as straight forward in all cases. The
specification of the language do allow for augmenting the Object
prototype; however, doing so changes the way for-in loops can be used
when function constructors are chained which is also allowed by the
specifications.
Object.prototype.foo = 123;
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
};
function Employee(name, department) {
this.name = name;
this.department = department;
}
Employee.prototype = new Person();
Employee.prototype.getDepartment = function (id) {
return this.department;
};
window.onload = function() {
var giselle = new Employee('Giselle', 'lingerie');
var props = [];
for (var p in giselle) {
props.push(p); // Oops foo gets pushed into props
}
console.log(props.join(', ')); // Firefox firebug
props = [];
for (var p in giselle) {
// Yes filters out foo but also the name
// and getName properties
if (giselle.hasOwnProperty(p)) {
props.push(p);
}
}
console.log(props.join(', ')); // Firefox firebug
}
I think that you would suggest using parasitic inheritance for this
but the argument here is what the specifications allow. Yes the above
implemention is ugly but if random mashups are the concern then the
above situation is in the mix to consider as well. In this case the
use of hasOwnProperty filters out more than desired.
Peter