问题描述
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
$ c $每个关于github的例子,这个应该使SocialMiner对象的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从函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!