开发者

Class keyword in Javascript

开发者 https://www.devze.com 2022-12-11 03:42 出处:网络
According to this art开发者_运维知识库icle it should be a Javascript 2.0 way to define class. However, I never saw that in practice. Thus the question. How to use class keyword and what is the differe

According to this art开发者_运维知识库icle it should be a Javascript 2.0 way to define class. However, I never saw that in practice. Thus the question. How to use class keyword and what is the difference between Javascript 1.x way of doing things?


I know this is a old post, but as of today i.e with the advent of ECMAScript 6 we can declare javascript classes.

The syntax goes as follows :

class Person{
  constructor(name){
    this.name = name;
  }
  printName(){
    console.log('Name is '+this.name);
  }
}
var john = new Person('John Doe');
john.printName(); // This prints 'Name is John Doe'

A complete guide to this can be found in this post


The reason you never saw the class keyword used in practice is that all the current implementations of JavaScript are 1.x.

JavaScript 2.0 was merged into ECMAScript 4 which was rather unpopular and so never made it into the real world.

So to answer your question, how do you use the class keyword? You can't.


Summary

In ES6 the class keyword was introduced. The class keyword is no more than syntactic sugar on top of the already existing prototypal inheritance pattern. Classes in javascript is basically another way of writing constructor functions which can be used in order to create new object using the new keyword.

Example

class Person {

  constructor(name) {
    this.name = name;
  }
  talk() { console.log('hi'); }
}

const me = new Person('Willem');

console.log(typeof Person) 
// logs function, Person class is just another constructor function under the hood

console.log(me.__proto__ === Person.prototype) 
// logs true, classes just use the same prototypal inheritance pattern which is used by constructor functions. 
// An object created with the new keyword gets a __proto__ property on it which is a reference to the prototype property on a constructor function.

In the above sample there can be observed in the first log that classes create from the class keyword actually are functions under the hood.

console.log(typeof Person) // logs 'function'

es6 classes use the same prototypal inheritance pattern which is used by constructor functions. Here is another example to demonstrate this behavior:

class Dog {

  constructor (name) {
      this.name = name;
  }
  
  bark () { console.log('bark') };

}

let doggie = new Dog('fluffy');

doggie.bark(); // logs bark


Dog.prototype.bark = () => console.log('woof');  
// changing the prototype of Dog, doggie refers to this with its __proto__ property. 
//Therefore doggie bark method has also changed.


doggie.bark(); // logs woof

The takeaway in the above example is that the bark method of any dog instance can be changed at runtime. This is because the bark method of any object created with the Dog class is just referring to this function.


You never saw it in practice because virtually nothing supports JavaScript 2.0. That draft is from a specification that died before being anything other than draft.


You can still build classes in JS of course using prototype!

var foo = function() {
  this.hurrah = "yay!";
  return this;
}

foo.prototype.doit() {
  alert(this.hurrah);
}


If you've a Java or C# background, here's how to define a class in JavaScript

var MyClass = function (f, l){//constructor 
    //private members
    var firstName = f,
        lastName = l,
        fullName = function () { //fullName is a private function
            return firstName + " " + lastName;
        };
    return {
        //public members
        getFullName: fullName 
    };
}

var output = document.getElementById('Output'); //<div id="Output"></div>
var myName = new MyClass("First", "Last");
output.innerHTML = myName.getFullName();


Just to add the ECMA5 way of class making.

Note that it does not have a constructor function this way (but you can trigger an init function if you like)

var Class = {
      el: null,
      socket: null,

      init: function (params) {

        if (!(this.el instanceof HTMLElement)) {
          throw new Error('Chat room has no DOM element to attach on.');
        }

        return this.doStuff();

      },
      doStuff: function (params) {
        return this;
      }
};

var instanceofClass = Object.create(Class, {
  el: {
    value: document.body.querySelector('.what ever')
  },
  someMoreData: {
    value: [0,5,7,3]
  }
}).init();
0

精彩评论

暂无评论...
验证码 换一张
取 消