This question already has answers here:
using key value pair of same object inside itself with 'this' in javascript
(3 answers)
Closed 7 years ago.
var foo = {
this.bar = function(){},
this.baz = new this.bar()
}
This won't work. I want foo.baz to be a foo.baz. How do I do it?
foo is an object literal, not an instance, so you can't use the "this" keyword in it (or semicolons, etc.)
Change your code to:
var foo = function() {
this.bar = function(){},
this.baz = new this.bar()
}
new foo();
Or:
var foo = {
bar: function() {}
}
foo.baz = new foo.bar()
Related
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 4 years ago.
Consider this simple TS script
class foo {
v: number = 1;
public bar() {
console.log(this.v);
}
}
var a = new foo();
var b = new foo();
document.getElementById('test').addEventListener("click", a.bar);
document.getElementById('test').addEventListener("click", b.bar);
and the HTML
<html lang="en">
<body>
<button id="test">Test</button>
</body>
</html>
I would expect to get 2 lines console output of number "1".
But NO! I get one undefined output
Lets take a look at the generated js file
var foo = (function () {
function foo() {
this.v = 1;
}
foo.prototype.bar = function () {
console.log(this.v);
};
return foo;
}());
var a = new foo();
var b = new foo();
document.getElementById('test').addEventListener("click", a.bar);
document.getElementById('test').addEventListener("click", b.bar);
//# sourceMappingURL=Test.js.map
For performance consideration TS decided to put the function on the prototype! so the addEventListener call was actually adding the prototype (static) function twice and its the same instance. That's why I'm only getting one output instead of two.
And the biggest issue is that the this inside the prototype function refers to the button and button doesn't contain a property called v!
If we do this in native js
var foo = function () {
this.v = 1;
var that = this;
this.bar = function () {
console.log(that.v);
}
}
var a = new foo();
var b = new foo();
document.getElementById('test').addEventListener("click", a.bar);
document.getElementById('test').addEventListener("click", b.bar);
we would get the desire result!
Is this a known issue for TS where you can't use the class method as event handler?
And how can I remove that handler after I added it?
You can. Just do:
document.getElementById('test').addEventListener("click", () => a.bar());
This question already has answers here:
How do JavaScript closures work?
(86 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 5 years ago.
I don't understand why this.name isn't the same as obj.name, basically why in this case this refers to the window object and not the obj object. In the code below, this.name is instantiated after obj.name..
function createNewPerson(name) {
var obj = {};
obj.name = name;
alert(this.name);
return obj;
}
Per MDN:
Inside a function, the value of this depends on how the function is
called. Since the following code is not in strict mode, and because
the value of this is not set by the call, this will default to the
global object , which is window in a browser.
So in your case you have this as the Window object, not the obj. You may get the obj context inside your function via binding it manually, for example:
function createNewPerson(name) {
console.log(this.name); // Hello
console.log(name); // World
}
var obj = {};
obj.name = 'Hello';
var salva = createNewPerson.apply(obj, ['World']);
But what you really need, as I can understand, is a function cunstructor and instantiating an object via new operator:
function createNewPerson(name) {
this.name = name;
}
var salva = new createNewPerson('Salva');
console.log(salva.name); // Salva
This question already has answers here:
How to define setter/getter on prototype
(6 answers)
Closed 7 years ago.
Is there any way to force a prototype's method (function) to be a property?
Say I have Foo with the method bar:
Foo.prototype.bar = function getBar() {
return something
}
To call bar, I can simply call foo.bar();, However I want bar to be a property of Foo, not a method, meaning foo.bar;. To do so, I can simply make getbar() a self invoking function:
Foo.prototype.bar = (function getBar() {
return something
})();
Now .bar is callable as a property. BUT the problem is that bar is only set when an instance of Foo is created, not every time .bar is called.
Is there any way I can get getBar() to be executed every time I call foo.bar?
You can do that using a getter:
function Foo () {
this.x = 1;
};
// Example of adding a getter to Foo.prototype
Object.defineProperty(Foo.prototype, 'bar', {
get: function getBar () {
return this.x++;
}
});
var tmp = new Foo;
tmp.bar; // 1
tmp.bar; // 2
tmp.bar; // 3
This question already has answers here:
Organize prototype javascript while perserving object reference and inheritance
(3 answers)
Closed 7 years ago.
In my little brain I can't explain how to refer correctly to method in object's prototype:
function A(){}
A.prototype.action = function(){}
A.prototype.dict = { action: this.action } // Mistake here.
var a = new A();
a.dict.action(); // -> undefined, but I expect a call of 'A.prototype.action' or other function if I override it in 'a'
You haven't really explained why you need this functionality, but the following should help you avoid the errors you're seeing. Whether this is good practice or not I leave up to you to research.
function A() {
var self = this;
this.dict = {
action: function() {
// by default, A.dict.action calls A.action
return self.action();
}
};
}
// Define A.action
A.prototype.action = function() {
console.log('prototype');
};
// Let's test it out
var a = new A();
a.dict.action(); // prints 'prototype'
// Override it on instance a
a.dict.action = function() {
console.log('overridden');
};
a.dict.action(); // prints 'overridden'
// Let's create a new instance of A: b
var b = new A();
b.dict.action(); // prints 'prototpye'
This question already has answers here:
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
Just to carify, I'm not asking the difference of function declaration and function variable.
For example:
var Klass = function() {};
Klass.prototype._fn1 = function fn1() {};
Klass.prototype._fn2 = function fn2() {};
So, my question is what is the purpose of doing this? Why can't just write:
var Klass = function() {};
Klass.prototype._fn1 = function() {}; // <-- note that the function has no name, it just be assigned to the object as a property
Klass.prototype._fn2 = function() {};
Basically this means you are adding the method _fn1() to Klass Constructor.
Klass.prototype._fn1 = function fn1() {};
And this method is available over the object which is made by using Klass() Constructor.
myObj = new Klass();
myObj._fn1() //you can access the method like this