How to create a property in a Javascript method

Asked

Viewed 85 times

1

Good evening everyone, I am a beginner in Javascript, and I have a question regarding the properties.

How can I create a property in a method in Javascript? I mean the methods because I’m learning POO.

For example when in an element we use:

document.querySelector('#elemento').className
document.querySelector('#elemento').firstChild

It would be possible in a method by calling it to use the . and then the property we want to use.

I tried something like:

const fn = function () {};
fn.prototype.name = 'Meu nome';

const run = new fn();
run.name // Meu nome
run.age // 20

By this means I create a function, and by means of the Prototype get what you wanted, perform a function and call a property.

I don’t understand yet, what’s the point of Prototype I will study it from now on. But as already informed as I could do something similar to a method?

class teste {
    constructor() {

    }

    metodoComPropriedades() {

    }

    outroMetodo() {
        // Estava imaginando ao como isso:
        this.metodoComPropriedades().propriedade
    }

}

2 answers

2


One could say that the prototype is the "predecessor of classes" for Javascript object orientation. However, it is worth emphasizing that the classes that were implemented in Ecmascript 2015 are only one syntactic sugar to the prototype, and are not a new object orientation model. Underneath the scenes, everything is still the prototype. :)

Thus, when you create a function in Javascript, it can end up being used as a "class", including methods and properties - static or instance; the latter can be defined through the prototype.

function Person(name) {
  // Corresponde ao construtor de uma classe.
  
  console.log('Objeto construído.');
  this.name = name;
}

// Definimos uma propriedade da instância.
Person.prototype.isHuman = true;

// Definimos uma propriedade da instância através do prototype.
Person.prototype.greet = function() {
  console.log(`Hello! My name is ${this.name}.`);
};

// E um método estático:
Person.a = function() {
  console.log('Método estático.');
};

Person.a();

const p = new Person('Luiz');
console.log(p.name);
p.greet();
p.a(); // Erro, já que `a` é um método estático.

Personally, I see no reason to use the prototype, since it is much more verbose than a class. See a code using classes that does exactly the same thing as the previous one:

class Person {  
  constructor(name) {
    console.log('Objeto construído.');
    this.name = name;
  }
  
  isHuman = true;
  
  greet() {
    console.log(`Hello! My name is ${this.name}.`);
  }
  
  static a() {
    console.log('Método estático.');
  }
}

Person.a();

const p = new Person('Luiz');
console.log(p.name);
p.greet();
p.a(); // Erro, já que `a` é um método estático.

So, go by which preference you want to use.


And in:

How can I create a property in a method in Javascript?

In the case of query selector, className or firstChild are not properties of the method querySelector in itself. They are, in fact, properties of the object that is returned by such methods. It is the same thing as doing this:

const fakeDocument = {
  querySelector: () => {
    // Note que estamos retornando um objeto do nosso método.
    return {
      firstChild: 'Foo',
      className: 'Bar'
    };
  }
};

console.log(fakeDocument.querySelector().firstChild); // Foo
console.log(fakeDocument.querySelector().className); // Bar

And it’s not even necessary to use prototype or classes to achieve that result. :)

  • 1

    Show, thank you so much for the attention @Luiz, I understood clearly now, your reply was very helpful, thank you!

1

What happens in the querySelector is that it returns an object (actually the reference) and therefore you have access to several properties

function foo() {
    return {
        bar: 'r',
        baz: 'z'
    };
}
console.log(foo().bar); //"r"
console.log(foo().baz); //"z"
console.log(foo()); //{"bar": "r","baz": "z"}

  • Opa thanks @Costamilam, I understand now, thank you so much for the reply!

  • let me ask you one more thing, I have the following scenario, I need to constantly check the form fields, to get some information from a dataset, a class, the value of that input etc, then for this reason I had the idea to create a method following your example and that of Luiz, to access every time I need x property, which will give me access to that element, because before I was always using foreach, IF to check, this way I arranged for this, is a more professional means? because before it was getting too repetitive.

  • It would be easier to answer this by seeing the code, it may be that yes, it is better to do as you said, but it may not, suddenly not even need the function. What is usually used is a framework or library, but as you are still studying Javascript, it would not be ideal to add one more thing

Browser other questions tagged

You are not signed in. Login or sign up in order to post.