javascript bind does work for function in a dictionary - javascript

so I have a function inside a dictionary
const Dict = {
func : () => {
console.log(this);
}
}
class A {
constructor() {
this.fun = Dict.func.bind(this);
}
}
const a = new A();
a.fun();
this gives me undefined, where I'm expecting this to be a
this binding seems to work if I move the function out of the dictionary. why doesn't bind work with dictionary?

Create a function as a property instead of using an arrow function, bind doesn't work for this with arrows
const Dict = {
func() {
console.log(this);
}
}
class A {
constructor() {
this.fun = Dict.func.bind(this);
}
}
const a = new A();
a.fun();

Related

Handle function in const class?

I have source code like this
const item = function(p) {
let model;
p.setup = function() {
}
}
I am not sure how should I call this class? function component?
What I want to do is add my function to this and call this function from outside.
const item = function(p) {
let model;
p.setup = function() {
}
function nextGame(){
console.log("test");
}
}
item.nextGame(); // error
However it doesn't work.
I am not familiar this style of javascript.
How should I add the function to this(is it class??) and call??
What you describe and demonstrate in your snippet javascript is an anonymous function, you could even say that it is a functional variable.
To access methods using dot notation, you need to create a class (or javascript object).
example using the keyword 'class':
class MyClass
{
var name;
var lastName;
constructor(_name, _lastname)
{
this.name = _name;
this.lastName = _lastname;
}
sayMyName()
{
window.alert(`${this.name} ${this.lastname}`);
}
}
Now create an instance of this class. Like this:
const myName = new MyClass("John", "Doe");
and now call with the method of your class using notation. Like this:
myName.sayMyName();
class Item {
// private field for whatever
// got passed to the constructor.
#value;
constructor(value) {
this.#value = value;
}
// prototypal methods with access to
// private fields and private methods.
setup() {
// do something with `this.#value`
console.log(this.#value);
}
nextGame() {
console.log("next game");
}
}
const item = new Item("OP's mysterious `p` value");
console.log({ item });
console.log('item.setup() ...');
item.setup();
console.log('item.nextGame() ...');
item.nextGame();
.as-console-wrapper { min-height: 100%!important; top: 0; }
For object-oriented programming in javascript there are a few methods, as mentioned in the comments.
1. Factory Function
A factory function is a simple approach, as it just creates and returns an object.
function Item(model) {
const item = {
model,
nextGame: () => { console.log('test') }
}
return item
}
const itemInstance = Item('Tesla');
itemInstance.nextGame()
console.log(itemInstance.model)
2. Constructor Function
Uses the new keyword to create an instance of the defined object type. It utilizes the function's prototype, which is accessible on all instances of the type.
function Item(model) {
this.model = model;
}
Item.prototype.nextGame = () => { console.log('test') }
const itemInstance = new Item('Tesla');
itemInstance.nextGame()
console.log(itemInstance.model)
3. Class
You could also use a Class. Classes in javascript are provided as an abstraction of functions.
class Item {
constructor(model) {
this.model = model
}
nextGame() {
console.log('test')
}
}
const itemInstance = new Item('Tesla');
itemInstance.nextGame()
console.log(itemInstance.model)

Why do we do this.xyz inside a function

I was trying to understand that why do we do this.xyz inside a function?
Like consider this function which we are calling like using foo()
function foo() {
this.value = "Shivom"
console.log(this.value) //Shivom
console.log(value) //Shivom
}
And alternate for this could be
function foo() {
value = "shivom"
console.log(this.value) //shivom
console.log(value) //shivom
}
Similarly, When In react I was using websocket someone asked me to do
class cryptoTicker extends Component {
componentDidMount() {
this.socket = openSocket('https://coincap.io');
let updateCoinData = [...this.props.cryptoLoaded];
this.socket.on('trades', (tradeMsg) => {
componentWillUnmount() {
this.socket.disconnect();
}
Instead of doing something like this
var socket;
class cryptoTicker extends Component {
componentDidMount() {
socket = openSocket('https://coincap.io');
let updateCoinData = [...this.props.cryptoLoaded];
socket.on('trades', (tradeMsg) => {
componentWillUnmount() {
socket.disconnect();
}
[Question:] So when and why do we use this.xyz inside a function? if someone can please explain me using the given two example above?
Well, in a nutshell:
var foo;
function bar(baz) {
foo = baz;
console.log(foo);
}
You can only have one foo value ever in your program this way. It's a singleton/global value.
class Foo {
constructor() {
this.foo = undefined;
}
bar(baz) {
this.foo = baz;
console.log(this.foo);
}
}
let a = new Foo;
let b = new Foo;
a.bar(42);
b.bar('fortytwo');
Using classes and object and setting properties on individual objects (this) allows you to have multiple independent instances of an object/value. That's the basis of OOP.

Capture `this` of caller inside class in JavaScript

Consider the following code:
class Abc {
funcAbc() {
console.log(this);
}
}
const abc = new Abc();
class Def {
constructor(func) {
this.func = func;
}
runFunc() {
this.func();
}
}
const def = new Def(abc.funcAbc);
def.runFunc();
I want this to be Abc when runFunc is called, but in the above implementation, this inside runFunc refers to Def. I understand this is happening because runFunc is a member of class Def. But is there any way I can capture 'original this', i.e. point this to Abc inside runFunc?
I cannot do const def = new Def(abc.funcAbc.bind(abc) because the consumer of class should not be bothered about setting the this context.
Note: This is not a theoretical question, it is an actual requirement in the project I am working on. The wrapper class takes in config, a part of which is a function. This function can also be a method on a class instance, using this inside it. Hence I need to preserve original this when calling the function from inside the wrapper class Def.
You are looking for bind() (or one of its variants).
class A {
constructor() {
this.hello = "hello";
}
run() {
console.log(this.hello);
}
}
class B {
constructor(func) {
this.func = func;
}
run() {
this.func();
}
}
const a = new A();
const b = new B(a.run.bind(a));
b.run();
When you bind() a function, it locks what this will be inside the function when the function is run, regardless of how it is invoked.
You could also wrap up the function in a closure:
class A {
constructor() {
this.hello = "hello";
this.run = ((self) => () => console.log(self.hello))(this);
}
}
class B {
constructor(func) {
this.func = func;
}
run() {
this.func();
}
}
const a = new A();
const b = new B(a.run);
b.run();
Or you could use the arrow function syntax. Note, this one requires the Babel class properties transform plugin to work:
class A {
constructor() {
this.hello = "hello";
}
run = () => {
console.log(this.hello);
}
}
class B {
constructor(func) {
this.func = func;
}
run() {
this.func();
}
}
const a = new A();
const b = new B(a.run);
b.run();
Using function.call(thisArg, args...) can set this to what ever you want. i.e., you could do:
class Abc {
func() {
console.log(this);
}
}
const abc = new Abc();
class Def {
constructor(source) {
this.func = source.func;
this.source = source;
}
runFunc() {
this.func.call(this.source);
}
}
const def = new Def(abc);
def.runFunc();
This solution assumes there will be a method on abc that is called func.

inherit javascript function prototype outside it closure

I am using JavaScript prototype chaining technique to chain functions as shown below:
var foo = (function () {
function fn(arg) {
if (!(this instanceof fn)) {
return new fn(arg);
}
this.arg = arg;
return this;
}
var func = function (element) {
return fn(element);
};
fn.prototype = {
bar: function () {
return this;
}
}
func.functions = fn;
return func;
}());
I would like to know how to access fn.prototype so I can add more functionality to the foo prototype outside its closure.
If I just simply do as follows, it won't work:
foo.prototype.baz = function () {
alert(this.arg);
}
foo("hello").baz();
However if fn assigned to the foo (func.functions = fn;) as it shown in the foo private closure I can do as follow and it will works:
foo.functions.prototype.baz = function () {
alert(this.arg);
}
foo("hello").baz();
Is there any other way to achieve this?
I think you are un-necessarily overcomplicating this. You can chain by simply doing this:
const foobar = function(){return this} // Initialize a new Object
const foo = text => {
const me = new foobar()
me.text = text
me.bar = a => (alert(me.text+": "+a), me)
return me
}
foo('A').bar('Test').bar('Test chained')
// Update the foobar class with baz
foobar.prototype.baz = function() {alert('BAZ worked!');return this}
foo('B').bar('1').baz().bar('2')
Note: Click Run code snippet to see the output
That's it!
Edit:
You can also do this with ES6 classes like:
class foobar {
constructor(text) {
this.text = text;
}
bar(a) {alert(this.text+": "+a);return this}
}
const foo = text => new foobar(text)
foo('A').bar('Test').bar('Test chained')
// Update the foobar class with baz
foobar.prototype.baz = function() {alert('BAZ worked!');return this}
foo('B').bar('1').baz().bar('2')

Efficient way for Javascript inheritance

I have two javascript classes as
class1 = function(opt) {
function abc () {
}
function def () {
}
function xyz () {
}
};
class2 = function(opt) {
function abc () {
}
function def () {
}
function lmn () {
}
};
These two classes contain some common methods like (abc, def) and some specific methods like (lmn, xyz). Can anybody suggest me how to apply inheritance to this situation effectively, so that I can have common methods in one file and specific methods in respective files. I tried prototype method, but this is not working. So is there any other way to this.
Thanks.
Depending on whether these classes just share behavior (interface) or are actually subclasses of a common class, you should use either a mixin or prototypal inheritance respectively.
An example for prototypes:
function BaseClass () {
}
BaseClass.prototype = {
abc: function () {
},
def: function () {
}
};
function class1 () {
}
class1.prototype = new BaseClass();
class1.prototype.xyz = function () {
};
function class2 () {
}
class2.prototype = new BaseClass();
class2.prototype.lmn = function () {
};
And an example of mixins:
function BaseMixin (object) {
object.abc = BaseMixin.prototype.abc;
object.def = BaseMixin.prototype.def;
}
BaseMixin.prototype = {
abc: function () {
},
def: function () {
}
};
function class1 () {
BaseMixin(this);
}
class1.prototype = {
xyz: function () {
}
};
function class2 () {
BaseMixin(this);
}
class2.prototype = {
lmn: function () {
}
};
Javascript dont have classes
But you can systemise your code.Javascript inheritance is totally different from that of othe oop languages.
Here,We use prototypes and constructors.
**prototype==>**In simple words,I am used for extension purpose
**constructors==>**I am used for creating multiple instances.Any function can be used as a constructor by using the new keyword.
Just sample codes for understanding.
SAMPLE 1:BY USING OBJECT LITERAL
var Myobject = {
Function_one: function()
{
//some code
Myobject.function_three();
},
Function_two: function()
{
//some code
Myobject.function_three();//lets say i want to execute a functin in my object ,i do it this way...
},
Function_three: function()
{
//some code
}
};
window.onload = Myobject.Function_one //this is how you call a function which is in an object
SAMPLE 2:BY USING PROTOTYPE
function function_declareVariable()
{
this.a= 10; //i declare all my variable inside this function
this.b= 20;
}
function_declareVariable.prototype.Function_one = function()
{
//some code
Myobject.Function_three();
};
function_declareVariable.prototype.Function_two = function()
{
Myobject.Function_three();
};
function_declareVariable.prototype.Function_three = function()
{
alert(Myobject.a or Myobject.b)
//some code
};
var Myobject = new function_declareVariable();//this is how i instantiate
REFER 1:what are constructors ,prototypes
REFER 2:prototypal inheritance

Categories

Resources