...

View Full Version : A question about prototype object usage for OOP?



eko007
12-27-2011, 03:18 PM
Hello,

I'm trying to write my class with member properties and functions like below. What I want to learn is that is there any problem to use prototype object in the class that we want to use with it? I asked because I generally see that prototype object definition and member functions and properties created outside of the class unlike my class that I wrote like below.

Is there any problem writing my class like below?
Thanks.




function Point()
{
Point.prototype.x = this._x;
Point.prototype.y = this._y;

function _setX(x)
{
this.x = x;
}
Point.prototype.setX = _setX;


function _setY(y)
{
this.y = y;
}
Point.prototype.setY = _setY;


function _show()
{
alert(this.x + this.y);
}
Point.prototype.Show = _show;
}


function callMyClass()
{
var p = new Point();
p.setX(3);
p.setY(5);
p.Show();
}

Dormilich
12-28-2011, 10:51 AM
yes. the prototype is the code every object inherits. there is no need to repeat that in every object (instance) creation. therefore you write it outside the constructor. it’s also superfluous to write a function and later assign that to the prototype.


function Point() {}
// this.x & this.y can be assigned at runtime

Point.prototype.show = function() {
alert(this.x + this.y);
}

// unless you want some value verification for x & y, you don’t need a setter

var p = new Point;
p.x = 3;
p.y = 5;
p.show();

// using a setter with value verification (as of ECMAScript 262 5th Edition)
function Point()
{
function toNumber(num)
{
num = parseFloat(num);
if (isFinite(num) && !isNaN(num)) {
return num;
}
throw new TypeError("coordinate is not a number.");
}
var x, y;
Object.defineProperty(this, "x", {
get: function() { return x; },
set: function(val) { x = toNumber(val); }
});
Object.defineProperty(this, "y", {
get: function() { return y; },
set: function(val) { y = toNumber(val); }
});
}

Point.prototype.show = function() {
alert(this.x + this.y);
}

var p = new Point;
// throws an error, if coordinates do not evaluate as number
p.x = 3;
p.y = 5;
p.show();

eko007
12-28-2011, 04:29 PM
Thank you very much Dormilich, it helped me a lot and works like a charm. But one of my aim was to be able to benefit from intellisense to access my properties or local variables. Obviously you taught me to best practise to define properties but when I try to access to x and y variables by p object, Visual Studio's and Dreamweaver's intellisense haven't shown them.

Dormilich
12-28-2011, 11:54 PM
part of the problem is that JavaScript is a prototype-based Programming Language. Intellisense based on class-type languages (C, Java, etc.) can’t be applied without losing much of JS’s possibilities (e.g. changing/extending objects on run-time). or in other words: there are no classes in JS.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum