0

In my function (x) i declared a calling method to it's prototype, but that's not calling, instead i am getting error.

here is my function:

var x = function () {
    console.log('i am called');
    this.y('child called'); // getting error
}

x.prototype.y = function(msg){
    console.log(msg); 
}

x();

Live Demo

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247
  • 5
    [`new x()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new). Constructor functions don't (at least, by default) create the new instance objects themselves; they just prepare such objects once they've been created. – Jonathan Lonowski Jan 10 '14 at 13:36
  • I go with @JonathanLonowski, see [this](http://jsfiddle.net/34eqK/3/) – DontVoteMeDown Jan 10 '14 at 13:37
  • exactly, thanks. i am wrong today. – 3gwebtrain Jan 10 '14 at 13:38
  • I don't think saying y is a child of x is correct. y is a member of x (or property if you like that word better). It is a shared member because it's defined on the prototype. More information about prototype and constructor functions can be found here: http://stackoverflow.com/a/16063711/1641941 – HMR Jan 10 '14 at 13:50

2 Answers2

1

Could you please try this... LINK

var x = function () {
    alert('i am called');
    this.y('child called');
}

x.prototype.y = function(msg){
    alert(msg);
}

new x();
Vishal Patel
  • 953
  • 5
  • 11
0

That's because in JavaScript, "this" refers to the owner of the function. In this case, the owner of the function is the global scope, which has no function y. To fix this, you would have to do something like this:

var x = {};
x.prototype.myFunction = function() {
  alert('i am called');
  this.y('child called');
}

x.prototype.y = function(msg){
  console.log(msg); 
}

x.prototype.myFunction();

This is explained more in-depth here: http://www.quirksmode.org/js/this.html