Should favor "_this" instead of "self" in javascript? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In Airbnb JavaScript Style Guide, they mentioned "When saving a reference to this use _this."
// bad
function() {
var self = this;
return function() {
console.log(self);
};
}
// bad
function() {
var that = this;
return function() {
console.log(that);
};
}
// good
function() {
var _this = this;
return function() {
console.log(_this);
};
}
However, I read few books mentioned "self" is good. Like in AngularJS: Up and Running.
<script type="text/javascript">
angular.module('notesApp', []).controller('MainCtrl', [function () {
var self = this;
self.message = 'Hello ';
self.changeMessage = function () {
self.message = 'Goodbye';
};
}]);
</script>
So, could any one tell me the reason to use "_this" instead of "self"?

This is just personal preference. However, it's best to only use one option inside a project's codebase. So don't use _this in one function block, then that or self in the other..

As noted by others, this is purely a coding style preference. I would offer a suggestion: If your team's code base is interested in continuing to use lexical scoping for this, then consider using ES6's fat arrow function instead to avoid creating an unnecessary variable.
This of course all depends if your project is ready to implement ES6 features.

I would not use self as it is already in use as another pointer to the window object. See here (part way down page) for an example of using self like a variable (without needing to prefix it as window.self): https://developer.mozilla.org/en/docs/Web/API/Window/self

Related

Calling a function within a function from outside [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am having some trouble here trying to call function C from an onClick event on the page.
function leftArrowClicked() {
functionA(functionC);
}
function functionA() {
function functionB(w) {
function functionC() {
// do stuff
};
}
}
<div id="dashboard_left_arrow" onclick="leftArrowClicked()">Click</div>
But it's of course not working. Currently seeing 'functionC is not defined' in the console. I don't know much about nested functions, hence probably why my method isn't working. Any ideas?
You can use something called Modular Design Patterns. It goes something like this -- you can see that functionA is an function that is already invoked, so I can call functionB directly on that because it is returned inside an object. Calling functionC can be done on top of that.
var functionA = (function() {
function functionB(w) {
function functionC() {
// do stuff
return 'inside functionC';
}
return {functionC:functionC};
}
return {functionB:functionB};
})();
function leftArrowClicked() {
console.log(functionA.functionB('').functionC());
}
<div id="dashboard_left_arrow" onclick="leftArrowClicked()">Click</div>

Why to use $onInit in AngularJS? [duplicate]

This question already has an answer here:
When to use the AngularJS `$onInit` Life-Cycle Hook
(1 answer)
Closed 3 years ago.
In AngularJS, what is the purpose of the $onInit function if I can do the same initialization without that function?
For example this:
module.component("myComponent", {
...
controller: function() {
const $ctrl = this;
$ctrl.$onInit = () => {
$ctrl.var1 = "hello";
$ctrl.var2 = { test: 3 };
}
}
});
Can also be done like this:
module.component("myComponent", {
...
controller: function() {
const $ctrl = this;
$ctrl.var1 = "hello";
$ctrl.var2 = { test: 3 };
}
});
Is there some case where $onInit is necessary?
Per the AngularJS docs
Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element).
This gives you two guarantees:
All controllers on this element have been constructed
The pre & post linking functions for this element have not been executed
In contrast to your first method, where neither of these facts are guaranteed (though the second one is highly probable).
In addition, as a matter of style and readability, it makes it very clear to a potential reader/reviewer that this is code that you as the developer intended to run upon initialization of this controller.

Javascript function call within function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am using VueJS with GoogleMaps to perform actions on a map. Therefore I wrote this function setup:
methods: {
// Init GIS
init: function() {
initGISMap(this.$els.map);
},
updateGIS: function() {
getAutoCompletePlace(function(place){
searchMarker.setPosition(place.geometry.location);
autocompletePlace = place;
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
self.updateIncidentForm();
});
},
updateIncidentForm: function() {
console.log("UpdateIncidentForm");
getAddressComponents(function(components) {
this.autoCompleteAddress = components;
this.setIncidentAddressFields(components);
});
},
(...)
I want to call the updateIncidentForm function, when the getAutocompletePlace performs. The error I get in my console is:
bundle.js:11073 Uncaught TypeError: self.updateIncidentForm is not a
function
Which is strange, as it is a function as defined in the code? Do I need to call the function differently?
You are calling self.updateIncidentForm() in your callback function, but you don't actually define the variable self anywhere.
Presumably, you meant to write something like:
updateGIS: function() {
var self = this; // <--- you forgot this line!
getAutoCompletePlace(function(place){
// (irrelevant code omitted)
self.updateIncidentForm();
});
},
The line var self = this saves a reference to the object you called the updateGIS() method on into the local variable self, so that you can use it inside the anonymous callback function you pass to getAutoCompletePlace() (where the value of this will be something different).
BTW, in modern (ES5.1+) JavaScript, another way to achieve the same result would be to use bind() to fix the value of this inside your callback, like this:
updateGIS: function() {
getAutoCompletePlace(function(place){
// (irrelevant code omitted)
this.updateIncidentForm();
}.bind(this));
},
The .bind(this) at the end of the callback function definition locks the value of this inside the callback to the value it had in the outer updateGIS() function.

Advantages of adding functions on the "this" instead of on the $scope

I came across a post which says that adding functions on $scope is the wrong approach and it should be added to this instead .
i.e -
//Don't do this
$scope.doStuff = function(){
//Really long function body
};
//Do this instead
var _this = this;
$scope.doStuff = function(){
_this.doStuff();
};
Taken from the 1st section of this post.
I suppose it is something related to memory duplicate ..
Can you explain why adding functions on this is more correct?

How to write a simple jQuery plugin [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I wanted to create simple plugin using jquery.
Also suggest me standard practice while writing jQuery plugin.
Please folks suggest me some better pointers.
a good starting pattern looks like:
(function($){
$.fn.yourplugin = function() {
};
}(jQuery));
A simple template I created years ago and still works great:
(function($) {
if (!$.myExample) { // check your plugin namespace does not already exist
$.extend({ // this will allow you to add your plugin to the jQuery lib
myExample: function(elm, command, args) {
// keep in mind, right here you might want to do a class or data check to determine which direction this call is going
// for example, upon init the plugin on an element you may add the plugin name as a class,
// this way, when it's recalled, you can see it alrady has that class and might be calling a command,
// thus make an if statemnt to push the process through
return elm.each(function(index){
// do work to each element as its passed through
// be sure to use something like
// return elm.each(function(e) { dor work });
// as your final statement in order to maintain "chainability"
});
}
});
$.fn.extend({ // this gives the chainability functionality seen with $ funcs like: $("#eleID").css("color", "red") <--returns original element object
myExample: function(command) {
return $.myExample($(this), command, Array.prototype.slice.call(arguments, 1));
}
});
$.myExample.props = { // Here you can establish specific properties to your plugin, prehaps even make them "Over-writable"
key1: "value",
key2: "value"
};
$.myExample.methods = { // Here you can establish specific methods/functions for your plguin to carry out and maintain your namespace as well
key1: function(param) {
/* do work */
},
key2: function(param) {
/* do work */
}
};
// This next part is not seen in many plugins but useful depending on what you're creating
$.myExample.init = function(param) { // If you have an initialize method to apply, namespace it in here and calll on initializing your plugin
var key = "value",
key2 = {
subKey: "value"
};
/*
/ run any number of initializing functions here
/ I prefer to make my param a value that can be a
/ string with a possible object
/ the string for holding a base configuration
/ the object for any change in properties or base values for that config
*/
};
$.myExample.defaults = { // establish base properties here that can be over-written via .props, but their values should never truly change
key1: "value",
key2: {
prop1: {
subKey1: "value",
subKey2: "value"
},
prop2: {
subKey1: "value"
}
},
key3: function(param) {
}
};
}
})(jQuery);
Summary and Best Practices while writing a jQuery Plugin
(function($){
// $('p').greenify() turns all text in p elements green.
$.fn.greenify = function() {
this.css( "color", "green" ); // set text color
return this; // for chaining;
};
})(jQuery);

Categories

Resources