函数没有我的方法可用

Function does not have my method available

本文关键字:方法 我的 函数      更新时间:2023-09-26

我已经为这个问题绞尽脑汁好几个小时了,到目前为止我已经看了大约30个在线教程。据我所知,我没有做错什么,但我有问题。我有一些测试代码:

TestPulse = function() {};
TestPulse.prototype.go = function() { alert('You just pulsed'); };
TestPulse.go();

我也试过:

function TestPulse() {};
TestPulse.prototype.go = function() { alert('You just pulsed'); };
TestPulse.go();

终于受够了,我只是从网上的一些原型和命名空间教程中抓取了一些代码,无论我做什么,我都会得到以下错误:

未捕获的类型错误:对象函数TestPulse(){}没有方法'go'

就像我说的,我不确定我做错了什么…这到底是怎么回事?当我调试时,我确实看到一个原型对象附加到函数上,带有构造函数等,所以我知道它在那里。问题在哪里?我是否不理解原型是如何工作的?

你没有TestPulse的实例…

TestPulse = function() {};
TestPulse.prototype.go = function() { alert('You just pulsed'); };
new TestPulse().go();
http://jsfiddle.net/HYWPk/

您需要创建一个TestPulse对象的实例来访问它的原型方法。

TestPulse = function() {};
TestPulse.prototype.go = function() { alert('You just pulsed'); };
var testPulse = new TestPulse();
testPulse.go();
http://jsfiddle.net/H2dnv/

Try

var a = new TestPulse;
a.go();

TestPulse.prototype.go();

TestPulse是您的(假设)类。您需要从它创建一个实例。

var myObject = new TestPulse();
myObject.go();

应该可以。