简体   繁体   中英

I don't understand how this code works in javascript

//classical JS does not provide a set data type--use JS object to build prime set:   
    var Set = function() {
        Set.prototype.add = function(o) {
        this[o] = true; 
      }
    }

    //Big-Time Important: 
    var s = new Set();
        s.add(2);
        s.add(3);
        s.add(5);
        s.add(7);
        s.add(11);
        s.add(13);
        s.add(17);
        s.add(19);
        s.add(23);   

This code works with a game in which it adds in a bunch of prime numbers and you must guess which one is the correct one. However the code: var Set = function () then goes into another function I don't understand the process of what is happening or how is that working with the set object created below.

this is object oriented java script style.. the prototype gives access to add variables and/or methods to the object in this case Set object. You can think of like below. Set is a class, you can create object by new Set()

function Set(){
 this.add = function(o){
   this[o]= true;
 }
} 

Before ES6 Javascript did not have built in in sets. So in this code you are creating a set.

var Set = function() {
        Set.prototype.add = function(o) {
        this[o] = true; 
      }
    }

The code above is javascript way of creating a "class".

Set.prototype.add = function(o) {
            this[o] = true; 
          }

The lines of code above is Javascript way of adding method called "add" to Set Class.

this[o] = true;

The line above is adding a property o and setting it's value to true. It is same as this.o = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM