Javascript access public methods from inside other public methods (same Object) [duplicate] - javascript

This question already has answers here:
Javascript "this" pointer within nested function
(9 answers)
Closed 6 years ago.
I have the following JS-Object:
var obj = function(){
this.var1 = "var1";
this.getvar1 = function(){
return this.var1;
}
this.call1 = function(){
this.getvar1();
}
}
all methods have to be public
all properties have to be public as well
Problem:
If i try to call a public method of the obj-Object from inside another public method of the obj-Object, the "this" keyword refers to the public method itself instead of the Object.
Is there a way to get around this?

You can assign this to a variable(self) and use that:
var obj = function(){
var self = this;
self.var1 = "var1";
self.getvar1 = function(){
return self.var1;
}
self.call1 = function(){
self.getvar1();
}
}

You just forgot to return from call1. Add return and it will work as expected:
var obj = function() {
this.var1 = "var1";
this.getvar1 = function() {
return this.var1;
}
this.call1 = function() {
return this.getvar1();
}
}
var a = new obj()
console.log( a.call1() )

Maybe you meant this:
const obj = {
var1: 'var1'
,getvar1() {
return this.var1
}
,call1() {
return this.getvar1()
}
}
console.log(obj.call1())

Related

Object object is not working as it should

I learned about prototype and proto and i think i understand it but this just doesn't make sense? Can somebody explain to me why accessing directly Object like this doesn't work.
function createObj() {
this.name = 'user';
this.prezime = 'user';
}
var obj1 = new createObj();
createObj.prototype.__proto__.toString = function () {
return 'works';
} //obj1.toString() returns 'works'
createObj.__proto__.__proto__.toString = function () {
return 'this works as well';
} //obj1.toString() returns 'this works as well '
//Then why this doesn't work:
Object.toString = function () {
return true;
}
From my understanding I am directly changing Object object.
So when I do obj1.toString() shouldn't it go to prototype and
then proto inside prototype and find toString() like it does from last two examples?
This is because you're setting a property on the Object constructor, not the Object prototype when you say Object.toString = ....
Trying to understand the difference between prototype and constructor in JavaScript
If you change Object.toString = ... to Object.prototype.toString = ... you get your desired result:
function createObj() {
this.name = 'user';
this.prezime = 'user';
}
var obj1 = new createObj();
createObj.prototype.__proto__.toString = function() {
return 'works';
} //obj1.toString() returns 'works'
console.log(obj1.toString());
createObj.__proto__.__proto__.toString = function() {
return 'this works as well';
}
console.log(obj1.toString());
Object.prototype.toString = function() {
return true;
}
console.log(obj1.toString())

Javascript define private variable [duplicate]

This question already has answers here:
Private properties in JavaScript ES6 classes
(41 answers)
Closed 5 years ago.
I want to build a class using javascript like in c, the main problem is private attribute.
var tree = {
private_var: 5,
getPrivate:function(){
return this.private_var;
}
};
console.log(tree.private_var);//5 this line want to return unaccessible
console.log(tree.getPrivate());//5
so I want to detect the access from tree.private_var and return unaccessible, and this.private_var return 5.
My question is: Is there any way to set private attribute in javascript?
EDIT: I saw this way
class Countdown {
constructor(counter, action) {
this._counter = counter;
this._action = action;
}
dec() {
if (this._counter < 1) return;
this._counter--;
if (this._counter === 0) {
this._action();
}
}
}
CountDown a;
a._counter is not accessible?
but
Define tree as a function instead of JavaScript object, define private variable in the function by var keyword, define public getting function by this. keyword and create a new instance by using the function
var Tree = function(){
var private_var = 5;
this.getPrivate = function(){
return private_var;
}
}
var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5
In ES6, you can do this but it is not supported by IE so I wouldn't recommend
class Tree{
constructor(){
var private_var =5;
this.getPrivate = function(){ return private_var }
}
}
var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5

Javascript Class loses reference to 'this' (using babel) [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
class UrlProvider {
constructor(root) {
this.root = root;
}
getUrl() {
return this.root + "/api/Situations";
}
}
class Repository {
constructor(urlProvider) {
this.urlProvider = urlProvider;
}
getAsync() {
var self = this;
return httpGetAsync(self.urlProvider.getUrl()).then(function(d) {
return d.map(x => new Situation(x));
});
}
}
class PromiseCacher {
constructor(cache, promise) {
var self = this;
self.cache = cache;
self.promise = promise;
}
runAsync() {
var self = this;
return self.promise().then(function (d) {
self.cache.set(d);
return d;
});
}
}
var urlProvider = new UrlProvider(appsettings.url);
var repository = new Repository(urlProvider);
var cache = new Cache();
var promiseCacher = new PromiseCacher(cache, repository.getAsync);
promiseCacher.runAsync()
When debugging the above code, chrome will crash inside the getAsync function of the repository because self.urlProvider is undefined.
Inside the repository getAsync function 'this' is referring to the instance of PromiseCacher which is what actually calls it.
What's going on?
Re-writing
var promiseCacher = new PromiseCacher(cache, ()=> repository.getAsync());
makes it work as I would expect.
That's because first of all repository.getAsync is not a promise. Instead it is a function. By storing the reference of repository.getAsync to a different object property you "alter" its this value. Take a look at the following example:
var obj = {
a: 42,
func: function(){
return this.a;
}
};
obj.func(); // 42
var b = obj.func;
b(); // undefined
The example is comparable to your code:
class Repository{
// urlProvider = ...
getAsync (){ /* ... */ }
}
var repo = new Repository(/* ... */);
repo.getAsync(); // works
var cacher = new PromiseCacher(/* ... */);
cacher.promise = repo.getAsync;
cacher.promise(); // does not work

Is multiple inheritance possible in javascript? [duplicate]

This question already has answers here:
does javascript support multiple inheritance like C++
(4 answers)
Closed 9 years ago.
I have a situation here. I have two modules(nothing but javascript function) defined like this:
Module1:
define(function(){
function A() {
var that = this;
that.data = 1
// ..
}
return A;
});
Module2:
define(function(){
function B() {
var that = this;
that.data = 1;
// ...
}
return B;
});
How to inhert both modules inside other module?
1) In js everything is just an object.
2) Javascript inheritance uses prototype inheritance and not classic inheritance.
JavaScript doesn't support multiple inheritance.
To have both of them inside the same class try to use mixins that are better anyhow:
function extend(destination, source) {
for (var k in source) {
if (source.hasOwnProperty(k)) {
destination[k] = source[k];
}
}
return destination;
}
var C = Object.create(null);
extend(C.prototype,A);
extend(C.prototype,B);
mixins:
http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/
inheritance in js:
http://howtonode.org/prototypical-inheritance
http://killdream.github.io/blog/2011/10/understanding-javascript-oop/index.html
Here you go a little demonstration of the functionality you want to achieve:
var obj1 = function() {
var privateMember = "anything";
this.item1 = 1;
}
var obj2 = function() {
this.item2 = 2;
}
var objInheritsBoth = function() {
obj1.call(this); // call obj1 in this context
obj2.call(this);
this.item3 = 3;
}
var x = new objInheritsBoth();
console.log(x.item1, x.item2, x.item3); // 1 2 3

Static self member in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static variables in JavaScript
How can i make a static encapsulation with self members in javascript?
such as in php:
class bar{
static public $foo;
static public function set() {
self::$foo = 'a';
}
}
bar::set();
In javascript:
var bar = function () {
????????
}
bar.set();
Thanks!
Simply define them as properties of bar.
bar.foo = null;
bar.set = function() {
bar.foo = "a";
}
Here's a nice overview:
var bar = function() {
// Private instance variables
var a = 1;
// Public instance variables
this.b = 5;
// Privileged instance methods
this.c = function() {
return a;
}
};
// Public instance methods
bar.prototype.d = function() {
return ++this.b;
}
// Public static variables
bar.foo = null;
// Public static methods
bar.set = function() {
bar.foo = "a";
}
Make a closure that creates the object and returns it. Inside the closure you can declare local variables, and they are private to the scope:
var bar = (function(){
var foo;
return {
set: function(){
foo = 'a';
}
};
})();
bar.set();

Categories