This question already has answers here:
What techniques can be used to define a class in JavaScript, and what are their trade-offs?
(19 answers)
Closed 8 years ago.
I come from C, C++, Java background. I want to create a struct/ class with some attributes and methods like:
MyClass{
string text;
array characters;
printText(){
print text;
}
printLen(){
print characters.length();
}
}
So next time I can create an object like above by just calling its constructor. How do I implement this in JavaScript? I am new to the programming principles followed in javascript, I want to create a custom data type here for reusability.
function MyClass () {
this.text = "";
this.characters = [];
}
MyClass.prototype.printText = function () {
console.log(this.text);
};
MyClass.prototype.printLen = function () {
console.log(this.characters.length);
};
var instance = new MyClass();
instance.text = "test";
instance.characters.push('a');
instance.characters.push('b');
instance.printText();
instance.printLen();
Related
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')
This question already has answers here:
JSON stringify ES6 class property with getter/setter
(7 answers)
Closed 4 years ago.
According to Martin, this syntax can be used to define a class in nodeJS:
class Person {
constructor() {
this.id = 'id_1';
}
set name(name) {
this._name = name;
}
get name() {
return this._name;
}
usage:
myPerson.name = "Saul"; // save the value in `_name` variable.
Slight problem with this convention is that calling JSON.stringify(myPerson) will print the following:
{
"_name": "Saul"
}
But if I remove the underline from the setter function, and write it as the following:
set name(name) {
this.name = name;
}
the setter function will recursively call itself forever. So is there no way of using this nice getter-setter syntax, and still use the name property? I'm running nodejs.
I dont see a problem at all here. If you deserialize it, it works as expected:
const saul = Object.assign(new Person, JSON.parse('{"_name": "Saul"}'));
console.log(saul.name);
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
This question already has answers here:
Why can I access TypeScript private members when I shouldn't be able to?
(10 answers)
Closed 6 years ago.
Why doesn't TypeScript encapsulate the private variables?
Given the following TypeScript:
private engine: string;
constructor(engine: string) {
this.engine = engine;
}
start() {
console.log('Starting engine ' + this.engine);
}
}
var car = new Car("Fiat");
car.start();
When I compile I get the following JavaScript:
var Car = (function () {
function Car(engine) {
this.engine = engine;
}
Car.prototype.start = function () {
console.log('Starting engine ' + this.engine);
};
return Car;
}());
var car = new Car("Fiat");
car.start();
The engine variable is public. Why doesn't TypeScript produce something more like:
var Car = (function () {
var _engine;
function Car(engine) {
_engine = engine;
}
Car.prototype.start = function () {
console.log('Starting engine ' + _engine);
};
return Car;
}());
For performance reasons. From Anders, "The problem with using constructor function local variables for private storage is that they can't be accessed from functions on the prototype object (which is what methods on a class become in the generated JavaScript). Instead you need to create local function objects and that consumes a lot more memory... As you can see, you need to create one function object per instance instead of a single function object shared by all instances through the prototype."
See here for a discussion: https://typescript.codeplex.com/discussions/397651
or here, "patterns for enforced private members in JavaScript have a lot of performance overhead. TypeScript is mainly targeting large applications, so compiling to code with performance overhead is not optimal"
This question already has answers here:
How do you create a method for a custom object in JavaScript?
(7 answers)
Closed 8 years ago.
How do you define JavaScript functions?
For example:
string.doSomething(); // OR
element.getSomeInfo();
I couldn't find anything on this, but maybe that's because it has a name I don't know.
EDIT
About four years later, let me rephrase this question to explain what I meant. I didn't know about objects, but essentially my question was "How do I define a function as a property of an object?". I wasn't necessarily differentiating between extending native Javascript classes (which is a bad idea) and just defining my own object with functions as properties.
So, to answer my own question, these are some different ways to do that:
const foo = {
bar: x => 1 / x;
}
so that, for example, foo.bar(4) returns .25. Another one:
function Rocket(speed){
this.speed = speed;
this.launch = () => {
this.speed = 'super fast and upwards';
}
}
So now one could define const Apollo = new Rocket('standing still'); and call Apollo.launch();
We can additionally extend such classes (including native ones) by
Rocket.prototype.stop = function(){
this.speed = 'Standing still';
}
and then call it using Apollo.stop();.
function Person(name) {
this.name = name;
}
Person.prototype.sayHi = function() {
return "Hi, I'm " + this.name;
}
var p = new Person("Jack");
p.sayHi() === "Hi, I'm Jack" // evaluates to true
Is this what you're looking for?
You can add a function as a member of an object.
For example:
var foo = {};
foo.sayHello = function () {
alert('hello');
}
foo.sayHello();
Add to prototype of the built-in String object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype)
String.prototype.doSomething = function(){
console.log('bingo!');
}
var aaa = "testing123";
aaa.doSomething();
I am not sure what element you mean here though.