Javascript OOP从函数返回值 [英] Javascript OOP return value from function

查看:78
本文介绍了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从函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆