简体   繁体   English

javascript原型方法未定义

[英]javascript prototype method not defined

Im trying to become more object orientated in my approach to doing things and ive run into an error where the console says a function is undefined. 我试图在做事的方法中变得更加面向对象,并且在控制台说函数未定义的情况下遇到错误。 I cant see how because i have other functions that run that have the same makeup. 我看不到是怎么回事,因为我运行的其他功能具有相同的功能。

i set up my object like this in my app.js: 我在我的app.js中设置了这样的对象:

var vid = new videoAPI(whichOs.type());

Then i set up my constructor in my lib.js: 然后我在lib.js中设置我的构造函数:

function videoAPI(osParam)
{
    this.os = osParam;
}

And create my methods the one I have issues with is this one in my lib.js: 在我的lib.js中创建我有问题的方法:

videoAPI.prototype.print = function()
{
    return this.os;
}

I then call in my app.js 然后我调用我的app.js

console.log(print()); 

I have two other functions that use this setup but i pass variables in. Can anyone tell me what im doing wrong? 我还有两个使用此设置的函数,但我传入了变量。有人可以告诉我即时消息做错了什么吗?

**edit. **编辑。 The line it fails on is is print(); 它失败的那一行是print(); I didnt mention i have this in a node.js project linking two js files together. 我没有提到我在将两个js文件链接在一起的node.js项目中拥有此功能。 this is the error: 这是错误:

ReferenceError: print is not defined
    at Object.<anonymous> (C:\Users\denis\Desktop\videoServer\app.js:36:13)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

You need to actually call the method off of the videoAPI instance. 您实际上需要从videoAPI实例中调用该方法。

var vid = new videoAPI('something');
console.log(vid.print()) // returns: something

If you're calling other functions without prefixing them with the videoAPI instance variable, then they exist globally. 如果您要在不使用videoAPI实例变量作为前缀的情况下调用其他函数,则它们会全局存在。

Based on the code provided, print is a prototype on the videoAPI object, but in the console log you're simply calling print. 根据提供的代码,print是videoAPI对象上的原型,但是在控制台日志中,您只是在调用print。 Change: 更改:

console.log(print());

To: 至:

console.log(vid.print());

It should fix your problem. 它应该可以解决您的问题。

EDIT: Looks like Seth beat me to it :P 编辑:看起来塞思击败了我:P

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

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