【问题标题】:Using objects with function in javascript在 javascript 中使用具有函数的对象
【发布时间】:2014-06-03 06:16:33
【问题描述】:

嘿,伙计们是 javascript 开发的新手。我已经了解了 javascript 对象,并且我已经用它编写了一些代码。我的代码

function afunction() { 
var num = 10;
return num;
}

afunction.randomfunction(function() {

return {

"name": "somename"

"age": 12
}

})

当我用 afunction.randomfunction.name; 调用函数时,它给了我类似的错误

" underfined is not a function"

我不知道为什么会这样。我需要的是我需要使用afunction.randomfunction.name;获取名称对象的值

我知道我做错了什么..希望你们能帮助我.找出我的错误。

【问题讨论】:

  • afunction.randomfunction.name 在此上下文中不是正确的代码,因为randomfunction 不存在,也不是afunction 的子代。为什么你有这个代码?你想达到什么目标?
  • afunction 没有randomfunction 的属性,所以afunction.randomfunction undefined
  • @Dai 我只想通过使用 afunction.randomfunction(function() { }) 获取名称的值,即 somename
  • @xdazz 你能给我提供一个例子来回答随机函数的添加属性吗?这样我可以更好地理解它
  • afunction.randomfunction 应该是什么?它应该是一个功能吗?如果是这样,您必须先将其定义为函数,然后才能调用它。

标签: javascript


【解决方案1】:

您正在尝试调用 randomfunction 并向其传递函数表达式,而不仅仅是分配函数表达式。

obj.foo(x) 更改为obj.foo = x

然后您可以调用它 — obj.foo() — 并从中访问返回值:obj.foo().property


function afunction() {
    var num = 10;
    return num;
}

afunction.randomfunction = function () {
    return {
        "name": "somename",
        "age": 12
    };
};

alert(afunction.randomfunction().name);

【讨论】:

  • 你能给我举个例子吗..我想调用两个函数,比如 function1.function2(function() { object_here } }) ..并从这里返回对象值
  • Err...我确实给你提供了一个例子!
  • 这是我想要的..我肯定会接受这个答案
  • 我怀疑如果我像 afunction.randomfunction(function() { return { name: somename }; }); 那样使用它会起作用
  • 这不起作用..它说 SyntaxError: Unexpected token )
【解决方案2】:

发生这种情况是因为函数 randomFunction 未在 aFunction 中定义。您需要将其定义为像这样的单独函数

function randomFunction(){
    //code
}

并通过randomFunction();调用它

或者如果你想创建一个带有公共函数的对象,你可以像这样创建它

function YourObject(){

    var num = 10; //think of this as a constructor

    this.getNum = getNum; //this "attaches" the getNum() function code to the getNum variable of YourObject
    function getNum(){
        return this.num;
    }

    this.randomFunction = randomfunction;
    function randomFunction(){
        //code
    }
}

之后您可以像这样调用对象的方法

var yourObject = new YourObject(); //instantiate
console.log(youObject.getNum()); //print the value of yourObject.num to console
yourObject.randomFunction(); //execute your random function

注意:在 JavaScript 中创建对象的方法还有很多,这只是其中一种。你可能会觉得Which way is best for creating an object in javascript? is "var" necessary before variable of object? 很有趣。

【讨论】:

  • 我不想这样做,我想像@quentin 说的那样做,但是当我运行他的代码时,它显示 SyntaxError: Unexpected token )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
  • 2018-02-15
  • 1970-01-01
相关资源
最近更新 更多