javascript : function and object...? -


can call function object? example:

function tip(txt){           this.content = txt;       this.shown = false;   } 

and:

var tip = new tip(elem.attr('title')); 

my questions:

  1. can call new function, object?
  2. the use of "this" made possible, because use function object?

you looking constructor concept.

all functions in javascript are objects , can used create objects:

function make_person(firstname, lastname, age) {     person = {};     person.firstname = firstname;     person.lastname = lastname;     person.age = age;     return person; } make_person("joe", "smith", 23); // {firstname: "joe", lastname: "smith", age: 23} 

however, in order create new objects of particular type (that say, inherit prototype, have constructor, etc), function can reference this , if called new operator return object of attributes defined on this in function - this in such cases references new object creating.

function make_person_object(firstname, lastname, age) {     this.firstname = firstname;     this.lastname = lastname;     this.age = age;     // note, did not include return statement } 

the key difference note between make_person , make_person_object calling new make_person() (as opposed make_person()) not different ... both produce same object. calling make_person_object() without new operator however, define this attributes on current this object (generally window if operating in browser.)

thus:

var joe = make_person_object("joe", "smith", 23); console.log(joe); // undefined console.log(window.firstname) // "joe" (oops)  var john = new make_person_object("john", "smith", 45); console.log(john); // {firstname: "john", lastname: "smith", age: 45} 

also, @robg points out, way of doing things creates reference prototype property of make_person_object on each "person" create. enables add methods , attributes persons after fact:

 // assuming came before make_person_object.prototype.full_name = "n/a"; make_person_object.prototype.greet = function(){      console.log("hello! i'm", this.full_name, "call me", this.firstname);  }; john.full_name // "n/a" john.full_name = "john smith";  make_person_object.full_name // still "n/a" john.greet(); // "hello! i'm john smith call me john" 

convention has constructor functions make_person_object capitalized, singularized , "nouned" (for lack of better term) -- have person constructor, rather make_person_object might mistaken ordinary function.

see also:


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -