473,785 Members | 2,811 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to initial a object properties by functions?

The following example are going to create an object to store the client
Information,
I would like to new the object to init all the properties by function:
setProperty()
Can I set the value to the object without using the global variable ?

Thank you.

///---------------The object -------------------------------
function clientENV {
var detect = navigator.userA gent.toLowerCas e();
this.os;
this.browser;
this.version;

setProperty();
}

///-------------Function------------------------------------
var theString, place, OS, browser, version;
function setProperty() {
if (checkIt('msie' )) browser = "Internet Explorer"
else if (checkIt('Firef ox')) browser = "Safari"
else if (checkIt('safar i')) browser = "Safari"
else if (checkIt('omniw eb')) browser = "OmniWeb"
else if (checkIt('opera ')) browser = "Opera"
else if (checkIt('webtv ')) browser = "WebTV";
else if (checkIt('icab' )) browser = "iCab"
else if (checkIt('konqu eror')) {
browser = "Konqueror" ;
OS = "Linux";
} else if (!checkIt('comp atible')) {
browser = "Netscape Navigator"
version = detect.charAt(8 );
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(p lace + thestring.lengt h);

if (!OS) {
if (checkIt('linux ')) OS = "Linux";
else if (checkIt('x11') ) OS = "Unix";
else if (checkIt('mac') ) OS = "Mac"
else if (checkIt('win') ) OS = "Windows"
else OS = "an unknown operating system";
}
}

function checkIt(string) {
place = detect.indexOf( string) + 1;
thestring = string;
return place;
}

Jul 6 '06 #1
9 1919
Cylix wrote:
The following example are going to create an object to
store the client Information, I would like to new the
object to init all the properties by function:
setProperty()
Can I set the value to the object without using the
global variable ?

Thank you.

///---------------The object -----------------------
function clientENV {
^^
There should be an arguments list in this (potentially empty) if this is
intended to be a function declaration.
var detect = navigator.userA gent.toLowerCas e();
Your - detect - variable appears to be local but you are using it as if
it was global (referencing it in other functions). Passing values
between functions via global variables is a very bad design pattern. You
should pass such values as arguments to the functions or properties of
objects for which those functions are methods.
this.os;
this.browser;
this.version;

setProperty();
}
If you mean that you want this - setProperty - function to act upon an
object created using - new clientENV() - then you make - setProperty -
into a method of the resulting object, probably by assigning it to the
prototype of - clientENV -:-

clientENV.proto type.setPropert y = function(){
if(something){
this.propertyNa me = 'x';
}
// etc.
};

- and call it in the constructor as:-

this.setPropert y();
///-------------Function-----------------------------
var theString, place, OS, browser, version;
function setProperty() {
if (checkIt('msie' )) browser = "Internet Explorer"
else if (checkIt('Firef ox')) browser = "Safari"
else if (checkIt('safar i')) browser = "Safari"
else if (checkIt('omniw eb')) browser = "OmniWeb"
else if (checkIt('opera ')) browser = "Opera"
else if (checkIt('webtv ')) browser = "WebTV";
else if (checkIt('icab' )) browser = "iCab"
else if (checkIt('konqu eror')) {
browser = "Konqueror" ;
OS = "Linux";
} else if (!checkIt('comp atible')) {
browser = "Netscape Navigator"
version = detect.charAt(8 );
}
<snip>

This is browser detection. Browser detection is an utterly futile
activity that has been abandoned in favour of better alternatives (at
least by everyone who knows what they are doing). If you are only just
starting to learn browser scripting (which is the obvious conclusion
from what you have posted here) then you should not even attempt to go
in the browser detection direction as eventually you will have to
re-trace your steps and learn proper feature detection (and everything
you write in the meanwhile will be very poor at best).

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

Richard.
Jul 6 '06 #2
Cylix wrote:
The following example are going to create an object to store the client
Information,
I would like to new the object to init all the properties by function:
setProperty()
Can I set the value to the object without using the global variable ?
Richard's response is pretty good, I prepared this before seeing his so
I'll post it anyway.

Without commenting on the actual example, what you are trying to do is
fairly common: you want a small object that also has methods to set its
own values, but you don't want all the methods replicated inside each
and every instance of the object. That's what JavaScript's prototype
inheritance is good at.

Have the constructor set the values, add the methods to the
constructor's prototype. As a cut-down version of your script:

// By convention, constructors start with a capital letter
function ClientENV()
{
// Set some default property values - not really necessary
// But keeps things tidy
this.os = 'default';
this.browser = 'default';
this.platform = 'default';

// Call setProperties, pass reference to the
// object being constructed
this.setPropert ies(this);
}

// Add the setProperties function as a method of the
// constructor's prototype so it's only one object, not
// a new instance for every object created
ClientENV.proto type.setPropert ies = function(obj)
{
obj.os = 'blah OS';
obj.browser = 'blah Browser';
}

var thisENV = new ClientENV();
alert(thisENV.o s + '\n' + thisENV.browser
+ '\n' + thisENV.platfor m);
Of course, using the above is moot since you are likely to only create
one 'thisENV' object anyway, so you might be better to use:

var thisENV = getENVPropertie s();

Where getENVPropertie s() returns an object with appropriate
properties/values:

function getENVPropertie s ()
{
var tempObj = {};
tempObj.os = 'blah OS';
tempObj.browser = 'blah Browser';
return tempObj;
}

I think that's simpler and the outcome is pretty much identical.

[...]

--
Rob
Jul 6 '06 #3
Richard Cornford wrote:
<snip>

This is browser detection. Browser detection is an utterly futile
activity that has been abandoned in favour of better alternatives (at
least by everyone who knows what they are doing). If you are only just
starting to learn browser scripting (which is the obvious conclusion
from what you have posted here) then you should not even attempt to go
in the browser detection direction as eventually you will have to
re-trace your steps and learn proper feature detection (and everything
you write in the meanwhile will be very poor at best).
I heard a lot of time about these thing, but sometimes ...
I really need to detect the client environment,
for example, I am going to use AJAX, but some of older browser does not
support that,
I need to mention the reason to the client and show the client a more
static page.
How can I present it better?

Thank you.

Jul 6 '06 #4
RobG wrote:
[...]
// By convention, constructors start with a capital letter
function ClientENV()
{
// Set some default property values - not really necessary
// But keeps things tidy
this.os = 'default';
this.browser = 'default';
this.platform = 'default';

// Call setProperties, pass reference to the
// object being constructed
this.setPropert ies(this);
Hey, musta been asleep ... don't need to pass this:

this.setPropert ies();
}

ClientENV.proto type.setPropert ies = function(obj)
{
obj.os = 'blah OS';
obj.browser = 'blah Browser';
}
And setProperties is:

ClientENV.proto type.setPropert ies = function()
{
this.os = 'blah OS';
this.browser = 'blah Browser';
}
--
Rob
Jul 6 '06 #5
"Cylix" <cy*******@gmai l.comwrites:
I really need to detect the client environment,
for example, I am going to use AJAX, but some of older browser does not
support that,
I need to mention the reason to the client and show the client a more
static page.
The test for the existence of an XMLHttpRequest object through the
known methods of acquireing one: global XMLHttpRequest constructor
or IE's ActiveX-controls.
There are known ways of checking this:
<URL:http://jibbering.com/2002/4/httprequest.htm l>
How can I present it better?
Make the page default to the static behavior if Javascript is disabled
or if there is no XMLHttpRequest object. Then change behavior if it
is possible.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 6 '06 #6
Cylix wrote:
Richard Cornford wrote:
><snip>
This is browser detection. Browser detection is an utterly
futile activity that has been abandoned in favour of better
alternatives (at least by everyone who knows what they are
doing). ...
<snip>
I heard a lot of time about these thing, but sometimes ...
I really need to detect the client environment,
In the event that you find a situation where you really need to detect
the browser being used you will have a problem as no mechanism is known
that can reliable do that, and examining the contents of the -
navigator.userA gent - string is easily the least discriminating strategy
available.
for example, I am going to use AJAX, but some of older
browser does not support that,
Some absolute brand new browsers will not support it either, but the
tests you are performing have little practical relationship with a
browsers ability (or even potential ability) to do AJAX. Logically, in
order to determine a browser's ability to do AJAX from browse detection
it would first be necessary to know which versions of which browsers
provide an XML HTTP request facility. Do you know, for example, which
minor version of IceBrowser introduced support for XML HTTP requests?

Knowing which versions of which browsers support XML HTTP requests it
becomes necessary to discriminate those browsers from the ones that do
not. While the code you are proposing using will not even discriminate
between IE and Opera (if Opera is using one of its variable User Agent
strings). How are you planning on identifying IceBrowser, let alone
discriminate between its versions sufficiently to identify its support
for AJAX?

However, on a browser as common as IE 6 the ability to employ XML HTTP
requests is guaranteed by the type or version of the browsers. The XML
HTTP request object is an ActiveX component outside of the browser so it
may be removed from the system independently from the browser. In
addition, even if the ActiveX object is installed on the system IE's
security settings are allowed to veto the availability of various
categories of ActiveX controls. And finally Internet security programs
may effectively block the use of ActiveX objects as a security measure.
I need to mention the reason to the client and show the
client a more static page.
How can I present it better?
The most reliable method of determining that you have an ability to
employ an XML HTTP request object is to attempt to instantiate one. If
you cannot do that then you may as well fall back to your alternative.
Though in reality any application of AJAX will depend on the browser
providing facilities well beyond the simple XML HTTP request object, so
they should also be feature detected as well.

Richard.
Jul 6 '06 #7
Thanks Rob and Richard.

I think I abuse to use the term AJAX,
Actually, I just doing the thing like AJAX but not using XML http
request.

My case is that, I need to using javascript to generate the whole
table,
you may think that it is a grid.

I have already test the js and get the interface in
PC {IE6, Firefox1.5}, Mac {Safari1.3.1, IE5.2}

As my boss using Mac IE5.2, I have to ensure it works on Mac IE5.2.
However, I find that one of important page cannot show on Mac IE5.2
properly,
the reason seems a bug of Mac IE5.2.

The bug is that when I using js(using createElement of
insertRow+inser tCell),
If the innerHTML(or createElement(' img') and then append on it)
contains <imgor any other HTML tag(I have tried IMG and SPAN only),
there is a great space around 300px on the cell, It doesn't matter that
I have other CSS to control the width.

One more problem that is Mac IE tabledata(td) seems doesn't have
colSpan property...

Jul 7 '06 #8
RobG wrote:
And setProperties is:

ClientENV.proto type.setPropert ies = function()
{
this.os = 'blah OS';
this.browser = 'blah Browser';
}
What is the differnece if I set the setProperties like this:
function clientENV {
....
....
this.setPropert ies=setP
}

function setP {
....
....
}

Actually, I will create this object when the pages onLoad,
I just need the property variable but no need the function
setProperties on the object,
Does there a way that when I "new clientENV", the properties is set
already and the clientENV only contain the proper value?

Thanks.

Jul 7 '06 #9
Cylix wrote:
RobG wrote:
>And setProperties is:

ClientENV.proto type.setPropert ies = function()
{
this.os = 'blah OS';
this.browser = 'blah Browser';
}

What is the differnece if I set the setProperties like this:
function clientENV {
...
...
this.setPropert ies=setP
}

function setP {
...
...
}

Actually, I will create this object when the pages onLoad,
I just need the property variable but no need the function
setProperties on the object,
Does there a way that when I "new clientENV", the properties is set
already and the clientENV only contain the proper value?
The only decision you have to make is whether to add the setP function
to the global (window) object or the ClientENV constructor's prototype.

Either way, the end result is the same - you have a setP object and an
ENV object with its properties set.

If you have a large and complex application, and setP only relates to
the ENV object, then making it a property of the constructor makes sense
from a house keeping (i.e. architectural) viewpoint. But if you have a
simple application - just a page with a few functions - then that seems
unnecessary. I wouldn't even have a constructor, I'd just do:

var ENV = setENVprops();

function setENVprops(){
var tObj = {};
// set tObj properties
return tObj;
}
--
Rob
Jul 7 '06 #10

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

Similar topics

3
2782
by: TekWiz | last post by:
I've got a system that automatically generates a form. I have it set up so that the backend will return to the inital form page with an error object in sessions data (assuming the backend detected invalid data or required fields not filled in) and the frontend will generate an initial value of items WITHOUT errors (so the user doesn't have to reenter valid info). This is the problem. The frontend generates the initial value attribute...
9
1603
by: Jimmy Cerra | last post by:
I am a little confused how the memory for objects is allocated in JavaScript. David Flanagan, in "JavaScript: The Definitive Guide," states that each property of a class takes up memory space when instantiated. So space is created for aMethod three times in this example: // Example 1 function aMethod() {/*stuff*/}; function AClass() { /*stuff*/
6
22535
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was 'myDog' without having to pass it as a parameter. //////////////////////////////// function...
16
25419
by: sneill | last post by:
How is it possible to take the value of a variable (in this case, MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name? In the following example I want 'oIcon' object to have the properties: mode1, mode2, and mode3. This seems simple but I can't quite figure it out... Any ideas anyone?
4
4018
by: Keith | last post by:
Hello - this started out as a minor annoyance - and now is starting to bother me more and more - I'm hoping someone can help me. I would like to have a combobox display - NOT initially be blank - but contain a value. However the value is just for user reference - not really one of the combobox choices. For example intially the combobox should equal the word Select - and the item values can be say 'one', 'two', and 'three'.
4
1886
by: Luke Matuszewski | last post by:
Here are some questions that i am interested about and wanted to here an explanation/discussion: 1. (general) Is the objectness in JavaScript was supported from the very first version of it (in browsers) ? What about the new syntax of creating a object using { 'propName1':'propValue1', 'propName2':'propValue2', 'propName3':{ /* another object */ } } - from what version of JScript/JavaScript it was supported (from what browsers versions) ?...
17
2237
by: Jef Driesen | last post by:
Suppose I have a datastructure (actually it's a graph) with one template parameter (the property P for each edge and vertex): struct graph<P>; struct vertex<P>; struct edge<P>; I also have an algorithm that modifies this datastructure. The basic outline of the algorithm is independent of the type of property. So I implemented a generic version of the algorithm and a function object for
7
3584
by: Steve | last post by:
I am building an object library for tables in a database. What is the best practice for creating objects like this? For example, say I have the following tables in my database: User: - Id - FirstName - LastName - CompanyId (many-to-one )
0
9480
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
10330
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
8976
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...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
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();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
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
2
3654
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.