Archive: 2017/4

0

JavaScript 面向对象

构造函数构造函数也是一个函数,通过new运算符可以生成一份实例同时把this绑定到实例上。JavaScript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。12345678910111213function Vehicle (engines) { this.engines = engines; } Vehicle.prototype.drive = function() { console.log(`engines=>${this.engines}`); } //实例 var car1 = new Vehicle(1); var car2 = new Vehicle(2); car1.drive(); //=> engines=>1 car2.drive(); //=> engines=>2 console.log(car1.constructor === Vehicle); //true console.log(car2.constructor === Vehicle); //true