issue with adding a method in object - javascript

I have this object:
var Point = {
step: function () {
alert("hello");
}
};
This works:Point.step();.
How to make it work with the [ ] notation? Meaning Point["property_name"].

It is Point["step"]();. Here is the snippet:
var Point = {
step: function () {
alert("hello");
}
};
Point["step"]();

Related

How do I call the function I pull out from an array in JavaScript?

I'm stuck with a problem, and I can't seem to figure out where to go. The code linked shows an array of 3 different functions. When the button is clicked it randomly splices one item out of the array after each click until the array is empty.
The cut out function shows fine in the console log, but I cannot figure out how to call the function and execute it. Anyone able to help me figuring out the correct way? I figured I'd use the new_numb like this (it does not work):
my_array[new_numb]();
Any help would be greatly appreciated!
Code for reference:
function first_function() {
console.log("test1");
}
function second_function() {
console.log("test2");
}
function third_function() {
console.log("test3");
}
Array.prototype.randsplice = function () {
var randomnr = Math.floor(Math.random() * this.length);
return this.splice(randomnr, 1);//removed extra variable
};
var my_array = [
first_function,
second_function,
third_function,
];
var button = document.getElementById("clicker");
button.onclick = function () {
if (my_array.length > 0) {
var new_numb = my_array.randsplice();
console.log(new_numb);
} else {
console.log('array is empty');
}
};
<button id="clicker">Click</button>
The array prototype function you're using returns an array with 1 index. So you need to access it with [0], then you can use apply() to call it.
new_numb[0].apply(null)
function first_function() {
console.log("test1");
}
function second_function() {
console.log("test2");
}
function third_function() {
console.log("test3");
}
Array.prototype.randsplice = function() {
var randomnr = Math.floor(Math.random() * this.length);
return this.splice(randomnr, 1); //removed extra variable
};
var my_array = [
first_function,
second_function,
third_function,
];
var button = document.getElementById("clicker");
button.onclick = function() {
if (my_array.length > 0) {
var new_numb = my_array.randsplice();
new_numb[0].apply(null)
} else {
console.log('array is empty');
}
};
<button id="clicker">Click</button>

Call function within closure with string in variable

I know this question has been asked several times on SO but I combed through about 12 questions and none have been able to help me out.
$(document).ready(function () {
var Joe = function(){
function introduce(petname){
alert(petname)
}
return {
introduce:introduce
}
}();
var Jane = function(){
function introduce(petname){
console.log(petname)
}
return {
introduce:introduce
}
}()
}
if I have the word joe stored in a variable how can I call the function
Joe.introduce('pluto')
assuming I have the word Joe stored in a variable fnc
fnc = "Joe";
I don't want to use eval. I have tried window[fnc.introduce('pluto')]()
as others have suggested but it does not work.
Try this! =)
var Joe = function(){
this.introduce = function(pet){
alert(pet);
}
}
var Jane = {
introduce : function(pet){
alert(pet);
}
}
$(function(){
new Joe().introduce('pluto');
Jane.introduce('food');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
The only way I can think to do this is something like this...
Store your functions in an object, then reference the function with object[fnc].
edit: updated original code to reflect OP's edits
fnc = 'Joe';
$(document).ready(function () {
var object = {
Joe: function () {
function introduce(petname) {
alert(petname)
}
return {
introduce: introduce
};
},
Jane: function () {
function introduce(petname) {
console.log(petname)
}
return {
introduce: introduce
};
},
};
object[fnc]().introduce('pluto');
object['Jane']().introduce('goofy');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

javascript prototype function - 'is not a function'

Problem:
I have a piece of code that throws an error: this.isEmpty is not a function,
and I cannot figure out why. Following is the fragment (jsfiddle):
function addAlbumGrid(){
const MainGrid = new AlbumGrid ()
return MainGrid
}
function AlbumGrid() {
MainGrid.call(this)
}
var parentPrototype = Object.create(AlbumGrid.prototype)
parentPrototype.constructor = MainGrid
MainGrid.prototype = parentPrototype
AlbumGrid.prototype.addPhotoBox = function () {
MainGrid.prototype.add.call(this)
}
function MainGrid(){
}
MainGrid.prototype = {
isEmpty: function() {
{
return false
}
},
add:function() {
if(!this.isEmpty())
{
return false
}
}
}
var AlbumGrid=addAlbumGrid()
AlbumGrid.addPhotoBox()
Following is code that works (jsfiddle):
function animal() {
}
animal.prototype = {
canWalk: function () {
return true
},
move: function () {
if(this.canWalk()) {alert ('moving')}
}
}
function bird() {
animal.call(this)
}
var animalProto = Object.create(animal.prototype)
animalProto.constructor = bird
bird.prototype = animalProto
bird.prototype.fly = function () {
animal.prototype.move.call(this)
}
let fluffy = new bird ()
fluffy.fly()
Searching for help I landed at this page, can it be that I am somewhere loosing the context of this, and it is pointing to something I don't want?
In that case, would a solution using composition be an option (object.assign(..))?
Or can it be anything else?
I hope somebody can shed a light.
Thank you...
Ps edit: I have now updated the code, the first 3 comments reflected an older version of this post.

JavaScript and object initialization

I'am decided to "go deeper" with javascript, and before ECMA6 to try to master ECMA5 skills, and now i am stuck with object creation and initialization, what version is better, more practical, better to read and so on.
Which one to stuck with and use as foundation. So what i am tried:
Version 1, and is most popular in guides found googling
;(function() {
var magic = magic || {};
magic.doStuff = function() {
alert('Magic');
};
window.magic = magic;
document.addEventListener('DOMContentLoaded', function() {
magic.doStuff();
}, false);
})();
Version 2, quite as same as version 1, just a little bit different syntax
(function () {
var magic = {
doStuff: function() {
alert('Magic');
}
};
document.addEventListener('DOMContentLoaded', function () {
magic.doStuff();
}, false);
})();
Version 3, this one is worst for me, difficult syntax, more space for mistakes, and i am not even sure is it writen correctly
(function () {
var magic = (function () {
magic.doStuff = function () {
alert('Wow!');
};
return magic;
});
document.addEventListener('DOMContentLoaded', function () {
(new magic()).doStuff();
}, false);
})();
Version 4, this one was shown to me by senior dev, not so popular in guides, or it's just i didn't noticed it, but after some explanation probably is my favourite.
(function() {
var magic = (function () {
function publicDoStuff() {
alert('Magic');
}
return {
doStuff: publicDoStuff
};
})();
document.addEventListener('DOMContentLoaded', function () {
magic.doStuff();
}, false);
})();
I like to keep it simple for simple objects
var magic = {
doStuff: function () {
alert('Wow!');
},
};
document.addEventListener('DOMContentLoaded', function () {
magic.doStuff();
}, false);
If you use many instances of an object, then its faster to use prototype
Magic = function() {
};
Magic.prototype.doStuff = function() {
alert('Wow!');
};

JavaScript binding for AJAX calls

I'm trying to bind the AJAX callback function to a certain scope, what am I doing wrong?
here is my code:
var MainApp = {
files:{
"A":{
url:"files/a.json",
content:""
},
"B":{
url:"files/b.json",
content:""
}
},
init:function () {
this.loadFiles();
},
loadFiles:function () {
for (var i in this.files) {
var f = function (data) {
console.log("callback",this);
};
console.log("binding",this);
f.bind(this);
$.get(this.files[i].url, f);
}
}
};
$(function () {
MainApp.init();
});
f.bind(this);
Function#bind doesn't alter the original function, it returns a new function bound to the parameter. You probably meant:
f= f.bind(this);
Try using call:
that = this;
$.get(this.files[i].url, function() {
f.call(that)
});

Categories

Resources