How to use JavaScript to define a class, javascript a class

Source: Internet
Author: User

How to use JavaScript to define a class, javascript a class

My original method is as follows:

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

Later, I saw another complicated and seemingly unnecessary statement:

function Dog(){  var privateVariable = 'secret';  var fn = function(){    //...  }  fn.prototype = {    makeNoise:function(){      alert('wangwangwang');    }  }  return fn;}

Here, the Dog function is actually a manufacturing function, which returns the real Dog class.
I feel that the advantage of doing so is better encapsulation.
For example, privateVariable is a private variable:

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

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

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

In this way, Dog is not a Dog ~

Later understanding:
The method for creating a new class directly overwrites the prototype object. In this way, prototype has no built-in attributes (arguments, call, apply, etc ).
The method for creating a class below seems better:

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


How does javascript define a class, attribute, and method? Write a program

// Define the Person class
Function Person (){
This. name = "Test"; // name attribute
This. age = 16; // age attribute
This. sex = "female"; // gender attribute

This. getName = function (){
// Obtain the name
Return this. name;
}
This. getAge = function (){
// Obtain the age
Return this. age;
}
This. getSex = function (){
// Obtain the Gender
Return this. sex;
}
}

Use

Var p = new Person ();
Alert (p. getName ());
Alert (p. getAge ());
Alert (p. getSex ());

How to define a boolean attribute in javascript?

Var a = true;
If (){
...
}

Note that the quotation marks are strings.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.