473,587 Members | 2,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

override toString for Object

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.

I have something like that

var myObj = new Object();
myObj.name = 'xxxx';
myObj.surname = 'yyyy';
.....
....

How can I override toString function?

There are some references on the net, like
http://developer.mozilla.org/en/docs...bject:toString

or....?

Please, help me.

Thanks in advance for the help.

See you.

Feb 13 '07 #1
8 8773
VK
On Feb 13, 11:35 pm, "kirkox" <mircovel...@gm ail.comwrote:
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.

I have something like that

var myObj = new Object();
myObj.name = 'xxxx';
myObj.surname = 'yyyy';
....
...

How can I override toString function?
Object object is the base for all other objects so by overriding
Object methods you are automatically influencing all other current and
future objects. So normally you do not touch Object itself, instead
create your own class of objects with desired properties.

function Person(name, surname) {
this.name = name || "John";
this.surname = surname || "Doe";
}

Person.prototyp e.toString = function() {
return this.name + " " + this.surname;
}

var p1 = new Person;

var p2 = new Person("Mary", "Brown");

alert(p1);

alert(p2);
Feb 13 '07 #2
Thanks for your reply.

I have something like that:

///////////////////
var copyoRow = new Array();

function getValues(){
....
for(var i = 0; i < numRows; i++) {
oRow = new Object();
oRow.name = ..getDocumentBy Id('..');
oRow.surname = getDocumentById ('...'); // only for thie example

copyRow.push(oR ow);
}
....
return copyRow;
}

....
////////////

Now, I hve to to create a string to append to server request, so I
need to using the properties of my Object.

similar to... oRow.toString() and then copyRow.toStrin g();

Thanks a lot.
Feb 13 '07 #3
kirkox wrote:
My question is simple...I'd like to override toString() function
such that it can works on Object.

I have something like that

var myObj = new Object();
myObj.name = 'xxxx';
myObj.surname = 'yyyy';
....
...

How can I override toString function?
<snip>

By assigning a reference to a function object to the - toString -
property of the object. That fucntion could, for example, be a named
global function. E.G.:-

function forObjectToStri ng(){
return (this.name + ' ' +t his.surname);
}

- and then:-

myObj.toString = forObjectToStri ng;

- or evaluating a function expressions and assigning its result to the -
toString - property of the object. E.G.:-

myObj.toString = function(){
return (this.name + ' ' +t his.surname);
};

Though in that case the function expression is possibly going to be an
inner function and its assignment may form a closure. See:-

<URL: http://jibbering.com/faq/faq_notes/closures.html >

Richard.

Feb 13 '07 #4
Ok now is ok.

bye

Feb 13 '07 #5
Thanks for your reply Richard.

Feb 13 '07 #6
thanks for your reply Richard.

bye

Feb 13 '07 #7
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.prototyp e.toString = function () {
return stringify(this) ;
};

See http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
Feb 14 '07 #8
On Feb 13, 5:55 pm, Douglas Crockford <nos...@sbcglob al.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.prototyp e.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.prototyp e.foo = 123;

function Person(name) {
this.name = name;
}
Person.prototyp e.getName = function() {
return this.name;
};

function Employee(name, department) {
this.name = name;
this.department = department;
}
Employee.protot ype = new Person();
Employee.protot ype.getDepartme nt = function (id) {
return this.department ;
};

window.onload = function() {

var giselle = new Employee('Gisel le', 'lingerie');

var props = [];
for (var p in giselle) {
props.push(p); // Oops foo gets pushed into props
}
console.log(pro ps.join(', ')); // Firefox firebug

props = [];
for (var p in giselle) {
// Yes filters out foo but also the name
// and getName properties
if (giselle.hasOwn Property(p)) {
props.push(p);
}
}
console.log(pro ps.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

Feb 14 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3985
by: Craig Schneider | last post by:
// Is there any way to override the XML Serialization of the following SimpleClass // to turn off the DefaultValue of a boolean? Sure, I can override the DefaultValue from // true to false, but that is not what I want/need. I really need to just override the fact // that the developer ever supplied a DefaultValue. Setting an override DefaultValue of null // or "new object()" errors. Any help would be appreciated.
7
4546
by: AWHK | last post by:
How can I force anyone who subclasses my class to override the ToString() method? Andreas :-)
8
1297
by: Sunny | last post by:
Hi all, The code as follow: using System; class A { public virtual void F() {
3
1131
by: portroe | last post by:
How Do i override the method toString()? Now it should return a string representation of an object, with various variables such as Lastname, Age and Marital status thanks Portroe
3
1721
by: Tony Johansson | last post by:
Hello!! You may correct me if I have made any wrong assumptions. Below I have some simple classes. When you have this t.ToString() below it's the ToString() method in Object class that is called and when you have this t.GetType() below it's the GetType() method in the Object class that is called.
3
1787
by: Publicjoe | last post by:
OK Folks, I am one confused puppy. Can someone please explain what the difference is and when to use each. I have a form with a button dropped onto it. Without actually doing anything to the button, I next add the following code: protected override void OnKeyDown(KeyEventArgs e) { System.Diagnostics.Debug.WriteLine(e.KeyCode.ToString()); base.OnKeyDown(e);
2
1430
by: Publicjoe | last post by:
OK Try again Can someone please explain what the difference is and when to use each. I have a form with a button dropped onto it. Without actually doing anything to the button, I next add the following code to the form: protected override void OnKeyDown(KeyEventArgs e) { System.Diagnostics.Debug.WriteLine(e.KeyCode.ToString());
8
2820
by: Phil Jollans | last post by:
Hi, I am having difficulty overriding the ToString() method of CultureInfo using Visual Studio 2005. Exactly the same code works fine with Visual Studio .NET 2003. What I am doing is adding objects which are derived from CultureInfo to a ListBox. I want the language name to be displayed in the native language, so I override the ToString() method to access the CultureInfo.NativeName
5
2381
by: taumuon | last post by:
I've got an object, Person, that supports IEquatable<Person>. It implements bool Equals(Person obj) as well as overriding bool Equals(object obj) I've got a container type that holds a member object of generic type T, that supports IEquatable<T>, and a method, DoComparisons(T obj) to compare the member object to the object passed in.
0
7924
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7854
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8219
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8349
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7978
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8221
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6629
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5395
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2364
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.