Declare method outside of class - javascript

i know i can add a method by doing:
point.prototype.move = function ()
{
this.x += 1;
}
But, is there a way to add a method to a class by assigning a function that is declared outside of it to one of its propertie?
I am pretty sure this can't work but it gives an idea about what i'am trying to do:
function point(x, y)
{
this.x = x;
this.y = y;
this.move = move();
}
function move()
{
this.x += 1;
}

The only reason your example doesn't work is because you are calling move() and assigning its result which is undefined.
You should just use a reference to the move function when assigning it.
function move()
{
this.x += 1;
}
function point(x, y)
{
this.x = x;
this.y = y;
this.move = move
}
Different ways to do it
// Attach the method to the prototype
// point.prototype.move = move;
// Attach the method to the instance itself
// var myPoint = new point(1,2); myPoint.move = move;

function point(x, y, move)
{
this.x = x;
this.y = y;
this.move = move;
}
function move()
{
this.x += 1;
}
var obj = new point(2, 5, move);

Related

accessing a methods property from another method

i want to access properties of a class method inside another method but i am getting NaN result. Isn't it possible to access the values of this.x and this.y from calSum()? Thanks
class Calc{
constructor(){}
num(){
this.x = 5;
this.y = 4;
}
calSum(){
this.sum = this.x + this.y;
console.log(this.sum);
}
}
const s = new Calc();
s.calSum();
Seems like this.x and this.y are not initialised in Calc constructor.
This results in this.x and this.y to be undefined.
undefined + undefined produces NaN.
I've updated constructor with initial values of zero for both x and y:
class Calc{
constructor(){
this.x = 0;
this.y = 0;
}
num(){
this.x = 5;
this.y = 4;
}
calSum(){
this.sum = this.x + this.y;
console.log(this.sum);
}
}
const s = new Calc();
s.calSum();

How to add object variable to an array using "new"?

I've got this object variable:
var Background = {
x: 0,
y: 0,
speed: 4,
initialize: function (x, y){
this.x = x;
this.y = y;
move: function(){
this.x -= this.speed;
}
};
And I'd like to create new object variable and add it to an array:
background_container = []
background_container.push(new Background())
But it throws an error:
"Uncaught TypeError: Background is not a constructor"
Although it works with normal:
function name() {}
var test_var = new name()
So my guess is that "new" works only for functions. But how can I do it with variable objects like the one before? (I want to have multiple of them in one array and not just multiple references to one object)
With ES5 and below you can create a function which acts as a constructor. Use this inside to bind properties to the current object which is returned from the new operator. Also you can leave the initalize function (if you intend to use this only one time) and pass parameters into the function or constructor directly.
function Background(x, y) {
this.x = x || 0;
this.y = y || 0;
this.speed = 4;
this.move = function() {
this.x -= this.speed;
}
};
var backgrounds = [];
backgrounds.push(new Background(1, 3));
console.log(backgrounds[0].x);
console.log(backgrounds[0].y);
With ES6 and higher you can use Ecmascript's new syntax for creating classes.
class Background {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
this.speed = 4;
}
move() {
this.x -= this.speed;
}
};
const backgrounds = [];
backgrounds.push(new Background(1,3));
console.log(backgrounds[0].x);
console.log(backgrounds[0].y);

How to extend a class inside a namespace in javascript?

var sl = sl || {}
sl.Shape = function(){
this.x = 0;
this.y = 0;
};
sl.Shape.prototype.move = function(x,y){
this.x += x;
this.y += y;
};
sl.Rectangle = function(){
sl.Shape.call(this);
this.z = 0;
};
The next line produces the error (Object prototype undefined, has to be Object or null). As far as I can see this is because Shape is "namespaced".
sl.Rectangle.protoype = Object.create(sl.Shape.protoype);
sl.Rectangle.protoype.constructor = sl.Rectangle;
How do I do this correctly?
You should use word prototype instead protoype.
You have misspelled the word "prototype" as Andrii pointed out, try this example:
(function() {
var sl = sl || {};
function Shape() {
this.x = 0;
this.y = 0;
}
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
};
function Rectangle() {
Shape.apply(this, arguments);
this.z = 0;
};
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
sl.Shape = Shape;
sl.Rectangle = Rectangle;
// expose
window.sl = sl;
}());
Usage
var shape = new sl.Shape();
var rect = new sl.Rectangle();

JS object inheritance with attributes

Im trying to get a very simple inheritance pattern for my Project going, extending from a base class into a specialized class. However, my specialized class's attributes are being overwritten by the parent's attributes.
Why is that and how can i fix it ?
thanks,
function Ship(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 0;
}
function Corvette(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 100;
Ship.call(this, className, x, y)
}
Corvette.prototype = Object.create(Ship.prototype);
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(Corvette.className) // "Smallish" - correct via parameter.
console.log(Corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(Corvette.constructor.name) // Ship
Why you have the same properties in the child object which are already in the parent's?
I suggest you to do
function Ship(className, x, y, speed = 0) {
this.className = className;
this.x = x;
this.y = y;
this.speed = speed;
}
function Corvette(className, x, y, speed = 100) {
Ship.call(this, className, x, y, speed);
}
Corvette.prototype = Object.create(Ship.prototype);
Corvette.prototype.constructor = Corvette;
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className) // "Smallish" - correct via parameter.
console.log(corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(corvette.constructor.name) // Ship
and if your browser supports some features of ES6 use this feature ES6 classes.
class Ship { // And also Ship is an abstractionm so you can use `abstract` keyword with it
constructor(className, x, y, speed = 0) {
this.className = className;
this.x = x;
this.y = y;
this.speed = speed;
}
}
class Corvette extends Ship {
constructor(className, x, y, speed = 100) {
super(className, x, y, speed);
}
}
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className) // "Smallish" - correct via parameter.
console.log(corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(corvette.constructor.name) // Ship
You only need to move Ship.call(this, className, x, y) at the start of Corvette function.
Also, next time, before posting code, check it is correct, you wrote console.log(Corvette) instead of console.log(corvette)
Another thing: you do not need to repeat params you do not want to overwrite
function Ship(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 0;
}
function Corvette(className, x, y){
Ship.call(this, className, x, y)
this.speed = 100;
}
Corvette.prototype = Object.create(Ship.prototype);
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className)
console.log(corvette.speed)
console.log(corvette.constructor.name)
You should invoke the parentclass contructor first and then override the properties, this way the properties set by Corvette will not be changed by the parent class i.e.:
function Corvette(className, x, y){
Ship.call(this, className, x, y)
this.speed = 100;
}

Javascript showing the function text instead of printing value on screen

function hex(x,y,side,isLast,color)
{//Hex object constructor.
this.x = x;
this.y = y;
this.side = side;
this.isLast = isLast;
this.color = color;
function multiply()
{
return this.x * this.y;
}
this.multiply = multiply;
}
var hexagon = new hex(22,22,20,0,1);
document.write(hexagon.multiply);
When loading index.htm, results that writes on screen the function instead of the returning value:
function multiply() { return this.x * this.y; }
:(
You forgot the ():
document.write(hexagon.multiply());
If you don't use (), Javascript will treat multiply as a variable and write out it contents - in this case, the code of the function.
You have to make sure that your javascript code is in <script> and </script> tags. So, it might read:
<html><head><script type="text/javascript">
function hex(x,y,side,isLast,color)
{//Hex object constructor.
this.x = x;
this.y = y;
this.side = side;
this.isLast = isLast;
this.color = color;
function multiply()
{
return this.x * this.y;
}
this.multiply = multiply;
}
var hexagon = new hex(22,22,20,0,1);
document.write(hexagon.multiply)
</script>
<body>
<!--Content here-->
</body>
</html>

Categories

Resources