Javascript OOP从函数返回值

编程入门 行业动态 更新时间:2024-10-13 18:23:48
本文介绍了Javascript OOP从函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

function SocialMiner() { var verbose = true; var profileArray = new Array(); var tabUrl; this.getTabUrl = function() { logToConsole(getTabUrl is called); chrome.tabs.getSelected(null,function(tab) { tabUrl = tab.url; logToConsole(tabUrl); }); 返回tabUrl; }`

然后我在SocialMiner ojbect上调用这个函数:

var pageUrl = miner.getTabUrl(); miner.logToConsole(pageUrl);

第一次调用 logToConsole 成功打印Url,而第二个说未定义。我是不是从函数返回相同的值?

更新:这是我如何定义logToConsole:

<$ (文本) { if(verbose) console.log(text); pre $ } this.logToConsole = logToConsole;

解决方案

在第二个示例中,您正在调用logToConsole,它是矿工对象的一个​​功能,不是。

miner.logToConsole this.logToConsole = function(text) { if(verbose) console.log(text); }

I have javascript object defined like this:

function SocialMiner() { var verbose=true; var profileArray=new Array(); var tabUrl; this.getTabUrl=function() { logToConsole("getTabUrl is called"); chrome.tabs.getSelected(null, function(tab) { tabUrl = tab.url; logToConsole(tabUrl); }); return tabUrl; } `

Then I call this function on SocialMiner ojbect like this:

var pageUrl=miner.getTabUrl(); miner.logToConsole(pageUrl);

What is the reason that first call to logToConsole successfully prints the Url, while second one says undefined. Am I not returning the same value from the function ?

Update: This is how I have defined logToConsole:

function logToConsole(text) { if (verbose) console.log(text); } this.logToConsole=logToConsole;

解决方案

In the second example, you are calling logToConsole as if it is a function of the miner object, which is is not.

miner.logToConsole

Edit

Per comments about github example, this should make the logToConsole function par of the SocialMiner object. However, I didn't read the class thoroughly, so proceed with caution with regards to how it is intended to be used.

this.logToConsole=function(text) { if (verbose) console.log(text); }

更多推荐

Javascript OOP从函数返回值

本文发布于:2023-11-26 02:30:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632294.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值   Javascript   OOP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!