user463231
user463231

Reputation:

How can I invoke a prototype function inside of a function object it b

var func_obj = function() {
    console.log('wat');
    this.my_proto_method();
};

func_obj.prototype.my_proto_method = function() {
    console.log('how do I programming');
};

​func_obj();​

I'm trying to get the above code to work. From what I've read this should work, not sure what I'm doing wrong here. Also setup a fiddle here

Upvotes: 1

Views: 36

Answers (2)

Ryan Lynch
Ryan Lynch

Reputation: 7786

You need to prefix your call to func_obj with the new prefix:

var func_obj = function() {
    console.log('wat');
    this.my_proto_method();
};

func_obj.prototype.my_proto_method = function() {
    console.log('how do I programming');
};

​var foo = new func_obj();​

Upvotes: 2

Anoop
Anoop

Reputation: 23208

To access prototype object/method with this you have to create new instance of func_obj. If you want to access prototype methods withod instance then you have to use prototype property as func_obj.prototype.my_proto_method().

var func_obj = function() {
    console.log('wat');
    this.my_proto_method();
   // if called without new then access prototype as : func_obj.prototype.my_proto_method()
};

func_obj.prototype.my_proto_method = function() {
    console.log('how do I programming');
};

​new func_obj();​

Upvotes: 2

Related Questions