1

I am trying to learn object oriented javascript. Why is this call to an object method not working (no alert)?

http://jsfiddle.net/hxPqJ/2/

When you click on the link, an alert is supposed to appear stating how old Bob is.

In case the link ever disappears, here is the HTML:

<a href="#" onclick="bob.say()">eh</a>​

and here is my javascript.

function guy(person_name) {
  this.name = person_name;
  this.age = 32;
  this.say = function() {
    alert(this.name + " is " + this.age);
    return false;
  }
}

  var bob = new guy("Bob");

​ Chrome Web Developer Console states

Uncaught ReferenceError: bob is not defined

However, I think I defined bob with var bob = new guy("Bob");.

3 Answers 3

5

You need to select one of the no wrap options in jsFiddle's left pane.

Otherwise, jsFiddle wraps your code in an event handler, and poor bob is stuck as a local variable.

Demo

Sign up to request clarification or add additional context in comments.

Comments

2

You are missing the closing } on say().

Beyond that, you must not return a value from the object constructor function. Doing so will simply set the variable bob to false.

function Guy(person_name) {
  this.name = person_name;
  this.age = 32;
  this.say = function() {
    alert(this.name + " is " + this.age);};
}

var bob = new Guy("Bob");

Note also that JavaScript conventions typically dicatate that an object constructor be capitalized like function Guy()

Here is the updated fiddle.

4 Comments

Thank you, not returning in the constructor makes sense. Without returning false though, how do I prevent the click event from bubbling up the DOM tree?
@DavidFaux: Put return false; in the inline handler.
@Michae​l: David's Javascript is actually fully valid, but mis-indented. See my answer.
@SLaks No, the original fiddle posted before the code was posted here was missing the } jsfiddle.net/hxPqJ
0

When I ran you code a message of

bob is not defined

showed up on the console. I think this is a JSFiddle quirk, since things worked when I changed things to set the onclick on the Javascript side instead of in the HTML.

<a href="#" id="foo">eh</a>

document.getElementById("foo").onclick = function(){ bob.say(); }

http://jsfiddle.net/hxPqJ/6/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.