Jump to content

Different OO JavaScipt approaches: please advise


448191

Recommended Posts

Functionally the same. Looking for arguments to prefer one over another.

 

function Bar1(){

var privateFoo = 'foo';

var privateFooMethod = function(){
	return privateFoo;
}
this.publicFoo = privateFooMethod();

this.publicFooMethod = function() {
	alert(privateFoo);
}
}
function Bar2(){

var privateFoo = 'foo';

var privateFooMethod = function(){
	return privateFoo;
}

return {
	publicFoo: privateFooMethod(),
	publicFooMethod: function() {
		alert(privateFoo);
	}
}
}

While they are similiar, your Bar2 returns an Object literal. It is easier to pass around the "this" keyword in Object Literals and you dont have to preface your "public" methods and properties with "this."

 

these are almost the same

 

var x = {

y: 'this is y',

z: function(){

console.log('this iz the z function');

}

};

 

function x(){

this.y = 'this is y';

this.z = function(){

console.log('this iz the z function');

};

}

 

The only difference, the biggest one, is that functions can be instantiated over and over again, but object literals are easier to work with. the extjs is a best of both worlds usage

I havent tested, but by looking at bar2, it looks like that creates more of a typical oo environment. I would assume that it is the same or similar to :

 

 

class bar2{

private $_foo;

private function manipulteFoo($val){

$this->_foo = $val;

}

public function changeFoo($val){

return $this->manipulateFoo($val);

}

public function getFoo(){

return $this->_foo;

}

}

I overlooked that difference.

 

It may be flexible to use object literals, it also makes it impossible to do any type checking. Try this in the Firebug console:

 

function Bar1(){

var privateFoo = 'foo';

var privateFooMethod = function(){
	return privateFoo;
}
this.publicFoo = privateFooMethod();

this.publicFooMethod = function() {
	alert(privateFoo);
}
}
function Bar2(){

var privateFoo = 'foo';

var privateFooMethod = function(){
	return privateFoo;
}

return {
	publicFoo: privateFooMethod(),
	publicFooMethod: function() {
		alert(privateFoo);
	}
}
}
document.write('<pre>');
document.write((new Bar1).constructor);
document.write('</pre>');
document.write('<pre>');
document.write((new Bar2).constructor);
document.write('</pre>');

 

function Bar1() {

    var privateFoo = "foo";

    var privateFooMethod = function () {return privateFoo;};

    this.publicFoo = privateFooMethod();

    this.publicFooMethod = function () {alert(privateFoo);};

}

 

function Object() {

    [native code]

}

 

It makes a little more sense now. Thanks.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.