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
Release: 2016-05-16 16:36:19
Original
1131 people have browsed it

This is how I originally wrote it:

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

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

Copy after login

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;
}

Copy after login

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
Copy after login

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

Dog.prototype = {
  //e...WTF??
}
Copy after login

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;};
}
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template