What you are trying to do is create an object for which the function is the constructor, but what the code actually does is set the talk
variable to the function. Do you want to:
function cat(name) { this.talk = function() { alert(" say meeow!" ) } } var myCat = new cat("felix"); myCat.talk()
edit:
Corresponding javascript tech talk: http://www.youtube.com/watch?v=ljNi8nS5TtQ
He talks about building objects with features in about 30 minutes. The code he publishes is:
function Circle(radius){ this.radius = radius; this.area = function(){ return this.radius * this.radius * Math.PI; }; } var instance = {}; Circle.call(instance, 5); instance.area(); // ==> 78.5398 var instance2 = new Circle(5); instance2.area() // ==> 78.5398 instance instanceof Circle // ==> false instance2 instanceof Circle // ==> true
And the corresponding quote:
A new keyword is simply an abbreviation that says "make a new object and call it a constructor ... the new keyword has no other meaning"
In other words, he says that when you use the
new
keyword, you define your variable as an object and call a function in the context of this object (
this
points to your object).
In addition, the new
keyword specifies the prototype of the newly created object for the prototype constructor. So, if we do this:
function Circle(radius){ this.radius = radius; this.area = function(){ return this.radius * this.radius * Math.PI; }; } var instance = {}; Circle.call(instance, 5); instance.__proto__ = Circle.prototype; // we set the prototype of the new object to that of the constructor instance.area(); // ==> 78.5398 var instance2 = new Circle(5); instance2.area() // ==> 78.5398 instance instanceof Circle // ==> true // this is now true instance2 instanceof Circle // ==> true
instance instanceof Circle
now true.
source share