Home >Web Front-end >JS Tutorial >How to define a class in JavaScript_Basic knowledge

How to define a class in JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:36:191130browse

This is how I originally wrote it:

function Dog(){
  this.name = 'hachi';
}

Dog.prototype = {
  makeNoise:function(){
    alert('wangwangwang');
  }
};

Later I saw another way of writing that was a little more complicated and seemed unnecessary: ​​

function Dog(){
  var privateVariable = 'secret';

  var fn = function(){
    //...
  }

  fn.prototype = {
    makeNoise:function(){
      alert('wangwangwang');
    }
  }

  return fn;
}

The Dog function here is actually a class-making function, which returns the real Dog class.
I feel that the advantage of doing this is better encapsulation.
For example, privateVariable here is a private variable:

var d = new Dog;
d.privateVariable //undefined

In addition, if you add a sentence at the end of the first example:

Dog.prototype = {
  //e...WTF??
}

This way Dog is no longer Dog~

Later understanding:
The above method of creating a new class directly overrides the prototype object. In this way, the original built-in attributes of the prototype are gone (arguments, call, apply, etc.).
The following method of creating a new class seems better:

var Dog = function(name){
  this.name = name;
  var privateVariable = 'you cannot see me.';
  this.getPrivate = function(){return privateVariable;};
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn