Reputation: 2269
How can I call the function inside of this 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
};
};
};
Upvotes: 3
Views: 167
Reputation: 22171
You can't reach a nested function from the outside of the first outer wrapping-function directly:
See more info about that here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope
Therefore, an easy solution would be to use a function expression, attached to the returned object.
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();
Upvotes: 1
Reputation: 82267
There are several options. A highly used approach is prototypes. A prototype will extend the object created with the functions defined on the prototype if the new
keyword is used. You can take advantage of this to expose functions.
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
};
};
Now the options, it can be called directly:
console.log(video().metadata());
It can be used as a function call and then referenced
var v = video();
console.log(v.metadata());
Or it can be explicitly instantiated and then referenced
var vid = new video();
console.log(vid.metadata());
This ensures that basically all uses of the function end up with the same functionality.
Upvotes: 4
Reputation: 15893
Make it a method of the new object:
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();
Upvotes: 8
Reputation: 95031
You can't, other than within said 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
};
};
metadata();
};
Upvotes: 5