如何在函数内部调用函数
How can I call a function inside of a function?
如何调用此函数内部的函数?
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();
相关文章:
- 调用函数内部的函数
- javascript函数内部的代码用逗号而不是分号分隔
- javascript无法重新定义函数内部的全局对象
- 如何从函数内部的这个变量中获取值
- appendChild在函数外部工作,但在函数内部不工作
- 在jquery函数内部设置来自jquery函数的var;t运行
- 一个'var'在函数内部声明
- 为什么(如何)'这'从函数内部调用回调时发生更改
- 函数内部未定义的输入值
- 在Meteor中如何将数据从函数内部复制到其他模板
- 如果在构造函数内部为else,则Javascript是可选的
- 我对“;返回true"嵌套函数内部;t工作
- jQuery 无法使用 AJAX 调用访问函数内部的函数参数
- javascript,将参数传递给函数内部的闭包中的回调
- 匿名自执行js函数内部的全局变量在外部仍然可用
- 使用PHP和Javascript在函数内部传递alphaneumeric值作为参数时出错
- 访问函数内部的Polymer方法
- 更改函数内部的全局变量而不调用它
- 如何在函数内部为jquery工具提示调用不同的var字符串
- 构造函数内部的事件处理