如何调用此函数内的函数?
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
};
};
};
答案 0 :(得分:8)
使它成为新对象的方法:
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();
答案 1 :(得分:5)
除了所述功能之外,你不能。
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();
};
答案 2 :(得分:4)
的 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());
这确保了基本上所有函数的使用最终都具有相同的功能。
答案 3 :(得分:1)
您无法直接从第一个外包装功能 外部达到嵌套功能:
点击此处了解详情: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();