Prototyping functions coding style [duplicate] - javascript

This question already has answers here:
Javascript: Overwriting function's prototype - bad practice?
(6 answers)
Closed 8 years ago.
When protyping functions (in most code I've seen) they are generally written like so:
function MyFunc() { }
MyFunc.prototype.render1 = function() { };
MyFunc.prototype.render2 = function() { };
MyFunc.prototype.render3 = function() { };
However this can be shortened like so:
function MyFunc() { }
MyFunc.prototype = {
render1: function() { },
render2: function() { },
render3: function() { }
};
From my understanding the shortended way will completely override the functions prototyped properties, as opose to adding one. Is there any other downsides to writing the protoyped functions in this manner?

I don't know any issues writing the second way - which I use also - because root prototype is Object, and you are passing an object so...

Related

Can't Access Class Property From Delegate Function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
Long-time .Net developer here, tasked with converting a bunch of old JS code to new ES6 JS modules. I'm trying to run the (you would think) simple code below, but when jumpToVideoNew is called, this.allowVidJump in the delegate function doesn't have access to the class property allowVidJump. I'm trying to set a simple timed delay so calling code can't hammer the jumpToVideoNew function repeatedly. I understand the concept that the variable loses scope, but I've tried setting _this = this; and using _this in the delegate as well with no success. Also tried passing a reference to the variable in to the function and accessing it that way, but also no luck. Spending 2 hours on something this simple is reminding me why I steer clear of javascript when possible.
export class WebUtility {
constructor() {
this.allowVideoJump = true;
this.delay = function () { this.allowVidJump = true; };
}
jumpToVideoNew() {
if (this.allowVideoJump) {
this.allowVideoJump = false;
setTimeout(this.delay, 1000);
}
}
}
Use an anonymous arrow function
The function keyword in JS creates a new scope as well as a new this (the function you just defined === this), so this.allowVidJump is essentially (function() {}).allowVidJump in that scope
Try something like this:
export class WebUtility {
constructor() {
this.allowVideoJump = true;
this.delay = () => { this.allowVidJump = true; }; // anonymous lambda
}
jumpToVideoNew() {
if (this.allowVideoJump) {
this.allowVideoJump = false;
setTimeout(this.delay, 1000);
}
}
}

No output from the object functions [duplicate]

This question already has answers here:
Referencing "this" inside setInterval/setTimeout within object prototype methods [duplicate]
(2 answers)
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 5 years ago.
This question is from an written test for a company. It looks very confusing. I thought it will print whatever this.name is set to. Bu when I typed the code it shows nothing. I have little knowledge about closures and I think it is related to the problem. I want a little explanation here.
function dd(name) {
this.name = name;
this.go = function() {
setInterval(function() {
return this.name;
}, 2000)
}
}
var tt = new dd("corolla");
tt.go()
You can't get the return value from setInterval in this way. Try with a callback as in the following snippet
function dd(name)
{
this.name=name;
console.log( name );
var _this = this;
this.go=function(cb)
{
setInterval(function() {
cb(_this.name);
},1000)
}
}
var tt=new dd("corolla");
tt.go(function(ret) {
console.log( ret );
})
Also, please note that inside setInteval the value of this is not the same as in the otter function. That's why var _this=this;

Unable To Access Private Properties In JavaScript Facade Pattern [duplicate]

This question already has answers here:
javascript "this" keyword not referring to correct thing
(3 answers)
Closed 7 years ago.
The Problem
In my "private" object for the facade pattern, I am defining methods and properties. When calling a method in this "private" object, I am getting Uncaught Typerror's saying that the method I am calling is not a function.
The Code
var lazySize = (function() {
var _ = {
images: [],
lazySizes: {},
resizeTimeout: null,
pageWidth: document.getElementsByClassName('crop_image')[0].offsetWidth,
resizeHandler: function() {
var i = 0;
for (var image in this.lazySizes) {
if (this.pageWidth < image) {
this.images[i++].src = this.lazySizes[image];
}
}
},
resizeThrottler: function() {
if (!this.resizeTimeout) {
this.resizeTimeout = setTimeout(function() {
this.resizeTimeout = null;
this.resizeHandler();
}, 66);
}
}
};
return {
init: function() {
window.addEventListener('resize', _.resizeThrottler, false);
}
};
}());
lazySize.init();
The Error
Uncaught TypeError: this.resizeHandler is not a function
The Question
Why am I unable to access the resizehandler method while inside resizeThrottler?
My understanding when using var rather than let, is that JavaScript is function scoped, so I am rather puzzled as to why I can't access it.
I am trying to improve my JavaScript, so if I am doing something really bad here, I would be very grateful if someone could point it out.
This is because this does not correspond to what you think it does.
You pass the resizeThrottler method as a reference for the browser to call, but when it does call it, the context is no longer your object, but window, which evidently does not have the same properties.
You could solve this as follows:
window.addEventListener('resize', _.resizeThrottler.bind(_), false);
This way you set the context of the method passed as handler to always run with _ as this.

More elegant way to call method from ajax callback function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 years ago.
I have a problem with javascript namespaces.
I want to call secondMethod from ajax callback function but I don't know how to get reference to it.
I have done it like that yet. But variable thisReference seems to me awkward. And whole construction is difficult to read.
So I'm writing there for help and answer how to rewrite it better.
var testObject = new TestObject();
testObject.firstMethod("hello world!");
function TestObject() {
var thisReference = this;
this.firstMethod = function(firstParam) {
ajaxFunc(firstParam, function(ajaxResult) {
thisReference.secondMethod(ajaxResult);
});
};
this.secondMethod = function(secondParam) {
alert("secondMethod " + secondParam);
};
}
function ajaxFunc(hello, callBack) {
callBack(hello);
}
Thanks a lot.
Ondra
Something like what you're doing is a common way to do it. Using:
var that = this;
or:
var self = this;
are common names to keep a hold of your original scope.
Another option (which I prefer) is to bind the this object to the method you're calling so that you have access to it in the callback. That would look like this:
this.firstMethod = function(firstParam) {
ajaxFunc(firstParam, function(ajaxResult) {
this.secondMethod(ajaxResult);
}.bind(this));
};
Hope that helps.

Does it matter which way named functions are declared? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
I see named functions exampled this way:
var clearClick = function() {
// do something
}
...and then used for binding like so:
$("#clear").bind(click, clearClick);
...or with the "shorthand" methodology thus:
$("#clear").click(clearClick);
But why not use a more "normal" (similar to other programming languages) construct like this:
function clearClick() {
// do something
}
It works the same, doesn't it? Is there any disadvantage to defining functions in this traditional way? Is the previous way just jQuerians flaunting their newfangledness?
This works Function expression
var clearClick = function() {
// do something
}
$("#clear").bind(click, clearClick);
This does not work Function expression. The order matters here.
$("#clear").bind(click, clearClick);
var clearClick = function() {
// do something
}
But when you declare your function using a function declaration the order does not matter.
One more advantage of the below syntax is that the function name appears in debugger.
function clearClick() {
// do something
}
One reason you might want to do it is how this works:
var clearClick;
$("#clear").click(clearClick);
clearClick = function() {
// do something
}
... lots of stuff in here ...
clearClick = function() {
// do something different
}

Categories