javascript inheritance methods are: 1. Using the call() method, you can write methods that can be used on different objects; 2. The apply() method, the syntax "apply(used as this object, to be passed to Array of function parameters)".
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
1. call() method
The call() method is the most similar method to the classic object impersonation method. Its first parameter is used as the object of this. Other parameters are passed directly to the function itself
function Huster(name,idNum,college) { this.name = name; this.idNum = idNum; this.college = college; this.course = new Array(); this.addCourse = function(course)//这个方法不能用prototype来定义,如果用的话,子类无法继承该方法 { //用原型prototype定义的方法可以用原型链来继承,call()方法和apply()方法都无法继承 this.course.push(course); console.log(this.course); }; } function Autoer(name,idNum) { this.college = ‘自动化‘; Huster.call(this,name,idNum,this.college);//Autoer使用call()方法来继承 Huster if (typeof Autoer._initialized == "undefined") { Autoer.prototype.sayHobby = function() //自己的方法可以用原型链prototype定义 { alert(this.college+‘人喜欢撸代码!‘); }; Autoer._initialized = true; } } var autoer1 = new Autoer(‘偶人儿‘,‘U123456789‘); //声明一个实例autoer1 console.log(autoer1.name,autoer1.idNum,autoer1.college,autoer1.course); autoer1.addCourse(‘logistics‘);//调用Huster的方法 autoer1.sayHobby(); //调用自身的方法
2. apply() method
The apply() method is almost the same as the call() method, the only difference is apply The () method has only two parameters, the first is used as the object of this, and the second is the array of parameters to be passed to the function. That is to say, the apply() method puts several parameters of the call() method into an array and passes them to the parent class
function Huster(name,idNum,college){ this.name = name; this.idNum = idNum; this.college = college; this.course = new Array(); this.addCourse = function(course)//这个方法不能用prototype来定义,如果用的话,子类无法继承该方法 { //用原型prototype定义的方法可以用原型链来继承,call()方法和apply()方法都无法继承 this.course.push(course); console.log(this.course); }; } function Autoer(name,idNum) { this.college = ‘自动化‘; Huster.apply(this,new Array(name,idNum,this.college));//Autoer使用apply()方法来继承 Huster if (typeof Autoer._initialized == "undefined") { Autoer.prototype.sayHobby = function() //自己的方法可以用原型链prototype定义 { alert(this.college+‘人喜欢撸代码!‘); }; Autoer._initialized = true; } } var autoer1 = new Autoer(‘偶人儿‘,‘U123456789‘); //声明一个实例autoer1 console.log(autoer1.name,autoer1.idNum,autoer1.college,autoer1.course); autoer1.addCourse(‘logistics‘);//调用Huster的方法 autoer1.sayHobby(); //调用自身的方法
[Recommended learning: javascript video tutorial]
The above is the detailed content of What are the inheritance methods in javascript. For more information, please follow other related articles on the PHP Chinese website!