如何在函数内部调用函数

How can I call a function inside of a function?

本文关键字:函数 内部 调用      更新时间:2023-09-26

如何调用此函数内部的函数?

var video = function() {
    this.name = "Name of Video";
    this.desc = "Short Description of Video";
    this.long = "Long Description of Video";
    function metadata(){
        return {
            name : this.name,
            shortDescription : this.desc,
            longDescription : this.long
        };
    };
};

使其成为新对象的方法:

var video = function() {
    this.name = "Name of Video";
    this.desc = "Short Description of Video";
    this.long = "Long Description of Video";
    this.metadata = function(){
        return {
            name : this.name,
            shortDescription : this.desc,
            longDescription : this.long
        };
    };
};
var videoObject = new video();
videoObject.metadata();

你不能,除非在所述函数内。

var video = function() {
    this.name = "Name of Video";
    this.desc = "Short Description of Video";
    this.long = "Long Description of Video";
    function metadata(){
        return {
            name : this.name,
            shortDescription : this.desc,
            longDescription : this.long
        };
    };
    metadata();
};

jsFiddle Demo

有几种选择。一种高度使用的方法是原型。如果使用 new 关键字,原型将扩展使用原型上定义的函数创建的对象。您可以利用这一点来公开函数。

var video = function() {
 if( !(this instanceof video) ){//ensure that we always work with an instance of video
  return new video();   
 }
 this.name = "Name of Video";
 this.desc = "Short Description of Video";
 this.long = "Long Description of Video";
};
video.prototype.metadata = function(){
 return {
    name : this.name,
    shortDescription : this.desc,
    longDescription : this.long
 };
};

现在的选项,可以直接调用:

console.log(video().metadata());

它可以用作函数调用,然后引用

var v = video();
console.log(v.metadata());

或者可以显式实例化然后引用

var vid = new video();
console.log(vid.metadata());

这确保了基本上该函数的所有使用最终都具有相同的功能。

您无法直接从第一个外部包装函数的外部访问嵌套函数:

在此处查看有关此内容的更多信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope

因此,一个简单的解决方案是使用附加到返回对象的函数表达式。

var video = function() {
    this.name = "Name of Video";
    this.desc = "Short Description of Video";
    this.long = "Long Description of Video";
    this.metadata = function(){
        return {
            name : this.name,
            shortDescription : this.desc,
            longDescription : this.long
        };
    };
};
new video().metadata();