Popularni postovi

Tuesday, 1 July 2014

Using functions in JavaScript

Using functions in JavaScript is not same as in C++,C#, Java..., for example:
If function make_person_object don't have return statement:

var Joe = make_person_object("Joe", "Smith", 23);
console.log(Joe); //RETURN undefined
console.log(window.firstname) //  "Joe" (oops) without the new operator it will define your this attributes on the current this object (generally window if you are operating in the browser.)

You MUST use "new" and then you will get your class:

var John = new make_person_object("John", "Smith", 45);
console.log(John); // {firstname: "John", lastname: "Smith", age: 45}

http://stackoverflow.com/questions/5958417/javascript-function-and-object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Douglas Crockford discusses that topic extensively in The Good Parts. He recommends to avoid the new operator to create new objects. Instead he proposes to create customized constructors. For instance:
var mammal = function (spec) {     
   var that = {}; 
   that.get_name = function (  ) { 
      return spec.name; 
   }; 
   that.says = function (  ) { 
      return spec.saying || ''; 
   }; 
   return that; 
}; 

var myMammal = mammal({name: 'Herb'});
In Javascript a function is an object, and can be used to construct objects out of together with the new operator. By convention, functions intended to be used as constructors start with a capital letter. You often see things like:
function Person() {
   this.name = "John";
   return this;
}

var person = new Person();
alert("name: " + person.name);**
In case you forget to use the new operator while instantiating a new object, what you get is an ordinary function call, and this is bound to the global object instead to the new object.
http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript#1598077

No comments:

Post a Comment