Javascript define private variable [duplicate] - javascript

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

Related

How to emulate super to override a parent method outside a class? [duplicate]

This question already has answers here:
Why wouldn't I use Child.prototype = Parent.Prototype rather than Child.prototype = new Parent(); for Javascript inheritance?
(3 answers)
Benefits of using `Object.create` for inheritance
(4 answers)
Closed last year.
To test my understanding of how classes work and how they can be emulated, I've done the following:
function Electronic(category) {
this.category = category;
this.state = 0;
}
Electronic.prototype.toString = function() {
return `The ${this.category} is turned ${this.state? "on" : "off"}.`;
}
function Computer(brand) {
Electronic.call(this, 'Computer');
this.brand = brand;
}
Computer.prototype = Electronic.prototype;
Computer.prototype.constructor = Computer;
Computer.prototype.toString = function() {
// how to get the super.toString() method here?
return `${Electronic.prototype.toString()} The brand is ${this.brand}.`;
}
c = new Computer('Dell');
console.log('' + c);
However, in trying to override the toString() method (while also retrieving the parent value), I'm running into a recursion error.
It seems the following works if I alias a parent method, but I'm wondering if it's possible to do it without changing one of the method names?
function Electronic(category) {
this.category = category;
this.state = 0;
}
Electronic.prototype._toString = function() {
return `The ${this.category} is turned ${this.state? "on" : "off"}.`;
}
function Computer(brand) {
Electronic.call(this, 'Computer');
this.brand = brand;
}
Computer.prototype = Electronic.prototype;
Computer.prototype.constructor = Computer;
Computer.prototype.toString = function() {
return `${Electronic.prototype._toString.call(this)} The brand is ${this.brand}.`;
}
c = new Computer('Dell');
console.log('' + c);

How to prevent updating attribute directly in js/ts class? [duplicate]

This question already has answers here:
Why can I access TypeScript private members when I shouldn't be able to?
(10 answers)
Closed 2 years ago.
class Animal {
privateAttribute
setPrivateAttribute(value) {
this.privateAttribute = value
}
}
new Animal().setPrivateAttribute('good way') //ok
new Animal().privateAttribute = 'not allowed' // no
I want to prevent update privateAttribute directly, the only way to set privateAttribute is call setPrivateAttribute function. What shold I do?
Please put all the private variable inside your constructor.
class Animal {
constructor() {
let privateAttribute = 'default';
this.setPrivateAttribute = newValue => {
privateAttribute = newValue
}
this.getPrivateAttribute = () => privateAttribute;
}
}
let newAnimal = new Animal()
// get variable value
newAnimal.getPrivateAttribute()
// Set new Value
newAnimal.setPrivateAttribute('New Value')

I can't use setter's in my javascript class because is not a function [duplicate]

This question already has answers here:
Getters \ setters for dummies
(14 answers)
Closed 3 years ago.
I try to use setter method with my class Test but my log return "TypeError: testObject.id is not a function"
class test {
constructor() {
this._id = 0;
}
get id(){
return this._id;
}
set id(newId){
this._id = newId;
}
}
const testObject = new test();
console.log(testObject.id); // return 0
testObject.id(12); //return TypeError: myTest.id is not a function
console.log(testObject.id);
I expect the ouput will be 12 but i obtain TypeError.
To use a setter, you do assignment, you don't write a function call:
testObject.id = 12;
Live Example (I've also changed the name to Test; the overwhelming convention in JavaScript is to capitalize constructor functions):
class Test {
constructor() {
this._id = 0;
}
get id(){
return this._id;
}
set id(newId){
this._id = newId;
}
}
const testObject = new Test();
console.log(testObject.id); // 0
testObject.id = 12;
console.log(testObject.id); // 12

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

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())

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

Categories