您好,欢迎访问一九零五行业门户网

javascript继承方法有哪些

javascript继承方法有:1、使用call()方法,可以编写能够在不同对象上使用的方法;2、apply()方法,语法“apply(用作 this 的对象,要传递给函数的参数的数组)”。
本教程操作环境:windows7系统、javascript1.8.5版、dell g3电脑。
1、call() 方法
call() 方法是与经典的对象冒充方法最相似的方法。它的第一个参数用作 this 的对象。其他参数都直接传递给函数自身
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‘); //声明一个实例autoer1console.log(autoer1.name,autoer1.idnum,autoer1.college,autoer1.course); autoer1.addcourse(‘logistics‘);//调用huster的方法autoer1.sayhobby();//调用自身的方法
2、apply() 方法
apply() 方法与call()方法几乎一样,唯一的区别就是apply()方法只有两个参数,第一个用作 this 的对象,第二个是要传递给函数的参数的数组。也就是说apply()方法把call()方法的若干个参数放到一个数组里,传递给父类
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‘); //声明一个实例autoer1console.log(autoer1.name,autoer1.idnum,autoer1.college,autoer1.course); autoer1.addcourse(‘logistics‘);//调用huster的方法autoer1.sayhobby();//调用自身的方法
【推荐学习:javascript视频教程】
以上就是javascript继承方法有哪些的详细内容。
其它类似信息

推荐信息