Differences in function declarations in a Javascript constructor function
I'm confused about the different ways to declare functions inside a constructor function.
function ClassName() {
this.one = function() {};
var two = function() {};
three = function()开发者_JS百科 {};
}
I know one is public and can be called by the outside and two is private. What are the semantics for three?
The example as you have provided would be a syntax error, as you need to use =
for assignment in that context.
three
if used with the correct assignment operator would be a global function that would exist outside of that scope. When you omit the var
keyword, the variable is assigned a property of the global object, which is window
in a browser.
jsFiddle.
When using var
, they become properties of the VariableObject in the execution context. You use them as normal variables.
Further Reading.
These are the ones that you can use in a constructor function:
function ClassName() {
// A function assigned to a property
this.one = function() {};
// A function assigned to a local variable
var two = function() {};
// A function declared locally
function three() {}
}
Only the first one ends up as a member of the object.
These are the ones that you can use in an object literal:
var objectName = {
// A function assigned to a property
one: function() {}
};
This is the first format
this is closeer to the static methods in other programming languages.
var ClassName = {
one: function() {},
two: function() {},
three: function() {}
}
ex:
ClassName.one();
and the other is:
function ClassName(){
this.one = function() {};
this.two = function() {};
this.three = function() {};
}
here you can do:
var obj = new ClassName();
obj.one();
In this case you need to instantiate the object before using the methods.
These are the two ways for classes in javascript... that i know of.
精彩评论