Can Object() take arguments?


#1

Exactly what it sounds like.

In Another Way to Create Objects we are instructed to create an object using a constructor with code new Object();.

It occurred to me that up to this point we have yet to put anything inside those parentheses and I was wondering if there is a use for them, and in that way? I did find something on using functions as object constructors or methods but not much addressing my specific question; perhaps I am not searching with the correct terms?

I also saw on MDN's page that I could potentially pass a value to the Object function, but there isn't much explanation on how it works. Presumably if I passed true to the function the object might return true, but how that even works and anything beyond that have me completely mystified; any pointers in the right direction would be greatly appreciated.

Thanks, everyone!
frisby


https://www.codecademy.com/courses/spencer-sandbox/1/5?curriculum_id=506324b3a7dffd00020bf661


// Our bob object again, but made using a constructor this time 
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
// Here is susan1, in literal notation
var susan1 = {
  name: "Susan Jordan",
  age: 24
};
// Make a new susan2 object, using a constructor instead
var susan2 = new Object();
susan2.name = "Susan Jordan";
susan2["age"] = 24;


#2

@msfrisby,
The 3th possibility to create susan is
by using the Class Object constructor
( by code-convention the =function-name= is Capitalized )

function Person(aName,anAge) {
      this.name = aName;
      this.age = anAge;
      }

// Make a susan3 object, using the =new= operator on the =Object constructor= like
var susan3 = new Person("Susan Jordan",24);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript

===T h e == m a i n == d i f f e r e n c e ================

Javascript is a so-called prototypal language.
Your Person class object constructor
will visualized look like

        OBJECT
  Object.prototype
           ^
           |
  Person.prototype  (( has no Method))
           |                              ^
           |                              | 
           |                    Person Class-Constructor
           ^                   | with this constructor
           |                   |  you can create Instance's of Person
   +Instance +      <---   using new Book("Susan Jordan",24);
   | of      |
   | Person  |
    The Person-Instance has access
     to Person.prototype.
     and is
      -chained- to the Object-prototype.

Using the construct notation

  Object.prototype
           ^
           |
   +---Object---+ 
   |            |
   |   susan2   |
   +------------+

Using the literal notation

  Object.prototype
           ^
           |
   +---Object---+ 
   |            |
   |   susan1   |
   +------------+

http://www.codecademy.com/forum_questions/545976cd282ae30d66001811
http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work
http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain


#3

Hi @leonhard.wettengmx.n,

Thank you so much for your thorough explanation. I have read your answer and links to the best of my current understanding and think I can grasp the basics of the class object constructor:

  • It, which by convention, starts with a capital letter, possibly inherits the properties of the object it was generated from, all the way up the chain until Object, which as prototype and/or [[prototype]] or proto or null property, I'm not sure, or perhaps it doesn't pass on its property at all.
  • The () after Object passes an empty hash to the constructor. The subconstructors are referred to using the term "Class" but are not "true" classes as in other languages such as Java and C++, and constructors are distinct from classes in the way inheritance works.
  • I thought I read also that it's important to distinguish between functions and something else (methods?), but embarrassingly I've forgotten what and haven't refound it.
  • I gather from forum posts that I too will be making these class object constructors soon in a future exercise.

I apologize in advance if my understanding is all upside-down.

However, I couldn't find anything whether it's possible to put something inside of the Object function's parentheses like so new Object(thing);, or did this just completely (instead of mostly, admittedly) go over my head?

Thank you again,
frisby


#4

@msfrisby,
As always,
on the lookout for
== discussions / opinions ==
you could google search the stackoverflow.com site like
javascript new object() with argument site:stackoverflow.com
and find a bunch of article's.......

or you google search
through
== the Book ==
javascript new object() with argument site:developer.mozilla.org


#5

Hi @leonhard.wettengmx.n,

Thank you for your further advice. I googled the suggested terms and found many of the topics seemed to overlap with the results of searching "passing arguments to new Object();" (e.g. Object.create(); and/or the class object constructor you've explained above). Last night, I started reading JavaScript & JQuery and think I have come to understand at least a little better the information you've kindly shared.

On that note, if I may ask, would it be correct to assume one cannot (or should not) pass arguments to new Object(); as, while it behaves like a function(?) it was not written with the ability to set properties or methods, and while one could "extend" the Object(); function if they so wished it is unnecessary and highly unrecommended?

*Update: I am re-reading the Crockford pages you recommended yesterday in another answer and I saw this:

When calling a function, it is not required that you pass a fixed number of parameters. Excess parameters are ignored. Missing parameters are given the value undefined. This makes it easy to write functions that deal with optional arguments.

Am I understanding correctly then that if I call new Object (thing);, thing, as an "excess parameter", will be ignored and the constructor will simply make a new object as with new Object();?

Thank you again for your time and help.


#6

@msfrisby,
Take the path
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
and then try to understand the creation of a parser
http://javascript.crockford.com/tdop/tdop.html


Object property naming conventions: camelCase or under_score?
Didn't declare a variable part II
#7

Hi @leonhard.wettengmx.n,

Thank you for your further suggestions! I’m sorry it took me a while to completely read (with some measure of comprehension that is) your recommended links…


First I went through the suggested MDN path and took notes to stay focused, I think I understood all of it but for:

Please note that function names of getters and setters defined in an object literal using “[gs]et property()” (as opposed to _define[GS]etter_ ) are not the names of the getters themselves […] legacy fallback).

I am thinking (hoping) once I learn getters and setters this section will make more sense.


Then I read the Crockford page and got the vague gist of what was going on… Reading Eli Bendersky’s TDOP blog post before rereading the Crockford page (again tried(!) to take notes) helped me understand it a little better.

NOTES: The next two~three sections summarize what I’ve learnt (hopefully correctly) from Leon’s links. For others who may happen upon this thread (or for my own future reference), I’ve included what I felt like were the most helpful of the additional reading I did to aid in comprehension…

First I didn’t understand what a “parser” is (I understand the everyday English verb “to parse”) and found a bit of disagreement… what I’ve gathered is that a parser is a program that scans code and sorts it into tokens to arrange into something called a syntax tree, which I understand can be manually recorded pictorially and illustrates “procedures”… From there the parser can give this information to an interpreter or compiler, or use it to check the code for syntactical errors… It seems a similar program to this is the basis for Crockford’s popular “Linter” “JSLint”…


From the intro I gather that this page illustrates the creation of a “TDOP”-style parser for a mini/subset of JS for this purpose, “Simplified JS”, perhaps the focus of which comprise the so called “Good Parts” in his book. It seems that the first step is to define “symbols”, which I think are the names of tokens*, which are a type of key-value pair, and so forth…I can generally understand what’s going on and vaguely explain (perhaps more so than comprehend) what each block of code is doing… Basically, the day-to-day lifestyle of a parser…

*link goes to a blog that re-explains Crockford’s page in the context of Java language.


Passing arguments/params to Object();


In the “Functions” section, the description reads:

It can take zero or more comma separated arguments. We look at the left operand to detect expressions that cannot possibly be function values.

From this I infer that in context of “Simplified JS” this may refer to illegal expressions such as "hello', and in context of JS I’d guess expressions at the discretion of the parser being used…

arguments, I believe


At this point I went to the recommended

Code
var test = new Object("hello");

for (var testKey in test) {
    console.log("test 1:");
    console.log(test[testKey]);
}

for (var testKeyB in test) {
    console.log("test 1b:");
    console.log(test, test[testKeyB]);
}


var test2 = new Object();
console.log("BEFORE test 2");

for (var test2Key in test2) {
    console.log("test 2:");
    console.log(test2, test2[test2Key]);
}


var test3 = new Object(3);
console.log("BEFORE test 3");

for (var test3Key in test3) {
    console.log("test 3:");
    console.log(test3, test3[test3Key]);
}



test4Method = function() {
    console.log("ran method!");
};
var test4 = new Object(test4Method);
console.log("BEFORE test 4");

for (var test4Key in test4) {
    console.log("test 4:");
    console.log(test4, test4[test4Key]);
}

and tried the below program, one “test” block at a time (test 1b came last…):

var test = new Object("hello");

for (var testKey in test) {
    console.log("test 1:");
    console.log(test[testKey]);
}

for (var testKeyB in test) {
    console.log("test 1b:");
    console.log(test, test[testKeyB]);
}


var test2 = new Object();
console.log("BEFORE test 2");

for (var test2Key in test2) {
    console.log("test 2:");
    console.log(test2[test2Key]);
}


var test3 = new Object(3);
console.log("BEFORE test 3");

for (var test3Key in test3) {
    console.log("test 3:");
    console.log(test3[test3Key]);
}



test4Method = function() {
    console.log("ran method!");
};
var test4 = new Object(test4Method);
console.log("BEFORE test 4");

for (var test4Key in test4) {
    console.log("test 4:");
    console.log(test4[test4Key]);
}

Test 1 returned h, e, l, l, o, which I thought meant new Object("hello") added the letters of string “hello” to the object as keys (my fault; I haven’t practiced with for in much yet). However test 1b showed that actually each key is the object { '0': 'h', '1': 'e', '2': 'l', '3': 'l', '4': 'o' } with each char of "hello" as its key.

Tests 2-4, in which I attempted to pass nothing (for control), a number, and a method, appear to create empty objects (I later amended the each console.log to include testX (X = test number) with the same results).


Conclusion


Between the reading and my program test I’m not really sure what to conclude… Apparently sometimes passing something to the Object function does result in augmentation of the object, but the results seem to be somewhat unpredictable (at least to me) and therefore not recommendable…

In addition, labs (presumably JSLint) recommends use of the shorter(?) object literal form which would forgo the opportunity to pass anything to the Object constructor.

I would guess that one could create a custom parser which accepts arguments to new Object(); but also suppose most any potential need for this would be superseded by the aforementioned Class Object constructor…


…However I am not confident the conclusions I’m drawing hit the mark. Did I manage to go down the road you’ve set me upon, Leon? Or am I lost in the woods…?

Thank you,
frisby