简体   繁体   English

jsFiddle无法识别类?

[英]jsFiddle doesn't recognize classes?

Originally reported here: Why is my jsfiddle Javascript class not defined? 最初在这里报道: 为什么我的jsfiddle Javascript类未定义?

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/ 小提琴位于: http : //jsfiddle.net/eggmatters/qeufnpoj/2/

Firebug reporting: "TypeError: baz.getMessage is not a function." Firebug报告:“ TypeError:baz.getMessage不是函数。”

This is because of the location of the bar.prototype . 这是因为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. 这意味着尚未定义getMessage() ,请注意,您正在使用Assignment = ,这意味着直到在代码中到达该行才定义getMessage() The solution is to have bar.prototype be defined first: 解决方案是首先定义bar.prototype

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

Fiddle Example 小提琴的例子

First, your JS isn't executing. 首先,您的JS没有执行。 If you change your JS load from "No wrap - in <head>" to "onLoad", it'll run. 如果您将JS负载从“ No wrap-in <head>”更改为“ onLoad”,它将运行。

Or, you can just wrap your JS in an onload function: 或者,您可以将JS包装在onload函数中:

$(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/ JSFiddle: http : //jsfiddle.net/5drcuwx5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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