public properties

J

josh

Hi If I have

function obj()
{
this.id;


function init()
{
this.id = 100;
}
}

and then:

var o = new Obj();

o.id; // print me undefined

why? private methods cannot access public properties?
 
K

kindy

init in the obj doesn't called.
- - - - - - - - -
function Obj(){
this.id;
function init(){
this.id = 100;
}
init.call(this);
}
var o = new Obj();
o.id;
- - - - - - - - -
and, i don't know why

init.call(this)

can't write as

init();
 
J

josh

init in the obj doesn't called.
- - - - - - - - -
function Obj(){
this.id;
function init(){
this.id = 100;
}
init.call(this);}

var o = new Obj();
o.id;
- - - - - - - - -
and, i don't know why

init.call(this)

can't write as

init();

yes sorry I've forgotten to write it:

function obj()
{
this.id;

function init()
{
this.id = 100;
}

init();
}

however the this is undefined because in the private function the
this keyword refers to the Window object! and not to the object in
which I'm staying to operate with.

Regards
 
K

kindy

yes sorry I've forgotten to write it:

function obj()
{
this.id;

function init()
{
this.id = 100;
}

init();

}

however the this is undefined because in the private function the
this keyword refers to the Window object! and not to the object in
which I'm staying to operate with.

the keyword this in a function will be always refers to the window,
unless:
1. function is invoked by call(obj) or apply(obj);
2. you assign function to an object's property, and then invoke it
like obj.fnName()


function Obj(){
function init(){
this.id= 100;
}
this.t= init;
this.t();
delete this.t;
}
- - - - - - - - -
function Obj(){
function init(){
this.id= 100;
}
init.call(this);
}
- - - - - - - - -
function Obj(){
var _this= this;
function init(){
_this.id= 100;
}
init();
}
- - - - - - - - -
function Obj(){
this.init();
}
Obj.prototype.init= function(){
this.id= 100;
};
 
K

kindy

the keyword this in a function will be always refers to the window,
unless:
1. function is invoked by call(obj) or apply(obj);
2. you assign function to an object's property, and then invoke it

3. new fnName()

:)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,153
Latest member
NamKaufman
Top