object-oriented
Process oriented
- Open the refrigerator door
- Put the elephant in
- Close the refrigerator door
object-oriented
- The elephant
- The refrigerator
- Hidden object (the hand or person that puts the elephant in the freezer)
Classes and objects
A class is a template for an object. It defines properties and methods that are common to the same set of objects
class
Es5 classes in the
Function People(name,age){this.name = name; this.age = age; // console.log('my name is:' +this.name); // console.log('my name is:' +this.name); // console.log('my name is:' +this.name); }} people.count = 0 people.getCount = function(){console.log(' current count:'+ people.count); } / / write here, instantiation of the object in the calling method, execute the People. The prototype. ShowName = function () {the console. The log (this. 'my name is:' + name); } let p1 = new People('aa',1) console.log(p1); p1.showName() People.getCount() let p2 = new People('bb',2) console.log(p2); p2.showName() People.getCount()Copy the code
Inheritance in ES5
Function Animal(name){this.name = name; } Animal.prototype.showName = function(){ console.log('name is:'+this.name); } function Dog(name,color){animal. call(this,name); Name this.color = color} Dog. Prototype = new Animal() Dog. Prototype. Constuctor = Dog let d1 = new Dog('aa','red') console.log(d1); d1.showName()Copy the code
Classes and inheritance in ES6
class People { constructor(name,age){ this.name = name; this.age = age; this._sex = -1; } get sex(){ if(this._sex === 1){ return 'male' }else if(this._sex === 0){ return 'female' }else{ return 'error' } } set sex(val){ if(val === 0 || val === 1){ this._sex = val } } showName(){ console.log(this.name); } static getCount(){// static method return 5}} people.count = 9 // Static method to define outside console.log(people.count); //9 console.log(typeof People); //function let p1 = new People('aa',11) console.log(p1); //People {name: "aa", age: 11, _sex: -1} p1.sex = 5; console.log(p1.sex); //error console.log(People.getCount()); //5 class Coder extends People{constructor(name,age,company){super(name,age) = company; } showCompany(){ console.log(this.company); } } let c1 = new Coder('cc',3,'tc') console.log(c1); //Coder {name: "cc", age: 3, _sex: -1, company: "tc"} c1.showName() //cc c1.showCompany() //tc c1.sex = 1; console.log(c1.sex); //maleCopy the code