Reputation: 5496
I am new to javascript object oriented programming. I wish to write a JS class which has some variable and methods.
I am trying this way:
function B(){
function makeB()
{
alert('make B');
}
}
var b = new B();
b.makeB();
It shows: Uncaught TypeError: Object #<B> has no method 'makeB'
Can't I declare a function like this? But by simply adding this
with the same, I am able to access it. Is it a local function within the variable.?
Apart from this, I tried this:
function B(){
function call()
{
alert('B call');
}
this.makeB = function(){
call();
alert('makeB');
}
}
var b=new B();
b.makeB();
Using this, makeB
can internally call call
but if I try to access this using prototype it doesn't
function B(){
function call()
{
alert('B call');
}
}
B.prototype.makeB = function()
{
call();
alert('callB');
}
Here again I am not able to call call
from makeB
as if call
is block specific function.
And what to do if I want any function to be private to a specific class and not to inherited by the child class. A method which can only be used by its object and not by object of inherited class.
function C(){}
C.prototype = new B();
C.prototype.constructor = C;
Say, I want object of C
to call makeB
but not call
. In this case what should I do.?
Upvotes: 0
Views: 94
Reputation: 2523
I'll try to answer in the order of your questions...
In your first example, the function call
is considered private
and will not be accessible outside of the object scope itself.
For your second question, it will be public
if you assign the function to this
or what I like to do, create a "private" variable called self or sometimes on late nights I might call it that. That way within other function calls and callbacks you always have scope of the object context.
function B(){
var self = this;
function call()
{
alert('B call');
}
self.makeB = function() {
call();
alert('makeB');
}
}
var b=new B();
b.makeB();
For the last I would say look at your inheritance chain and build your base with only the functions that will be shared by inheriting objects.
Hope this helps.
Upvotes: 1
Reputation: 8781
in order to declare publicly accessible function inside JavaScript object you have to use this
. By applying this
you actually expose this function as a property of an object
function Person(first,last) {
this.firstname = first;
this.lastname = last;
//private variable available only for person internal use
var age = 25;
//private function available only for person internal use
var returnAge = function() {
return age;
};
// public function available as person propert
this.askAge = function()
{
return returnAge ;
}
}
var john = new Person('John','Smith');
console.log(john.returnAge); // will return undefined
var johnsAge = john.askAge(); // will return 25
Upvotes: 1