简体   繁体   中英

jsFiddle doesn't recognize classes?

Originally reported here: Why is my jsfiddle Javascript class not defined?

However, upon my implementation, I'm seeing similar behavior but none of the answers appear to apply.

foo();
baz = new bar();
baz.getMessage();

function foo() {
    $('#foo').html("I am foo.");
}

function bar() {
    this.message = "I am bar.";

}
bar.prototype = {
    getMessage: function() {
        $('#bar').html(this.message);
    }
};

Fiddle located at: http://jsfiddle.net/eggmatters/qeufnpoj/2/

Firebug reporting: "TypeError: baz.getMessage is not a function."

This is because of the location of the bar.prototype . Specifically because it's after the creation of the instance and call and as such will not be defined yet:

baz = new bar();
baz.getMessage();
... 
bar.prototype = { ... }

Meaning that getMessage() was not yet defined, note that you are using an assignment = , meaning that getMessage() will not be defined until that line is reached in the code. The solution is to have bar.prototype be defined first:

bar.prototype = { ... }
...
baz = new bar();
baz.getMessage();

Fiddle Example

First, your JS isn't executing. If you change your JS load from "No wrap - in <head>" to "onLoad", it'll run.

Or, you can just wrap your JS in an onload function:

$(function() {
    ...
}

or

window.onload = function() {
    ...
}

Second, you need to declare the prototype before you try to execute:

foo();
bar.prototype = {
    getMessage: function() {
        $('#bar').html(this.message);
    }
};
baz = new bar();
baz.getMessage();

function foo() {
    $('#foo').html("I am foo.");
}

function bar() {
    this.message = "I am bar.";

}

JSFiddle: http://jsfiddle.net/5drcuwx5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM