Can you call a function as an object? For example:
function Tip(txt){
this.content = txt;
this.shown = false;
}
And:
var tip = new Tip(elem.attr('title'));
My questions:
- Can you call
newfor a function, as for an object? - The use of “this” is made possible, because we use that function as an object?
You are looking for the
constructorconcept.All functions in JavaScript are objects and can be used to create objects:
However, in order to create new objects of a particular type (that is to say, that inherit a prototype, have a constructor, etc), a function can reference
thisand if it is called with thenewoperator then it will return an object with all of the attributes that are defined onthisin the function –thisin such cases references the new object we are creating.The key difference to note between
make_personandmake_person_objectis that callingnew make_person()(as opposed to simplymake_person()) will not do anything different … both will produce the same object. Callingmake_person_object()without thenewoperator however, will define yourthisattributes on the currentthisobject (generallywindowif you are operating in the browser.)Thus:
Also, as @RobG points out, this way of doing things creates a reference to the
prototypeproperty ofmake_person_objecton each “Person” we create. This enables us to add methods and attributes to persons after the fact:Convention has it that constructor functions like
make_person_objectare capitalized, singularized and “nouned” (for lack of a better term) — thus we would have aPersonconstructor, rather than amake_person_objectwhich might be mistaken for an ordinary function.See also:
newoperator