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 thenewoperator it will define yourthisattributes on the currentthisobject (generallywindowif 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:
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: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 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.function Person() { this.name = "John"; return this; } var person = new Person(); alert("name: " + person.name);**
http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript#1598077
No comments:
Post a Comment