call()和apply()方法使用代码实例

快乐打工仔 分类:实例代码

本章节分享几段关于call()和apply()方法使用的代码实例。

需要的朋友可以做一下参考,关于两个方法的基本用法这里不做介绍,可以参阅相关阅读。

(1).call()方法可以参阅js call()一章节。

(2).apply()方法可以参阅javascript apply()一章节。

代码实例如下:

/*
 * 矩形
 */
function Rectangle(len,width) {
  this.len = len;
  this.width = width;
   
}
/*
 * 乘以
 */
function multiply(a,b) {
  return a * b;
}
// 矩形实例
var rectangle = new Rectangle(15, 30);
//求矩形面积
var proportion = multiply.call(rectangle,rectangle.len, rectangle.width);
console.log(proportion);
 
   
// 实现继承
function Persion(name) {
  this.name = name;
  this.sayHello = function () {
    return "欢迎来到,"+this.name;
  }
}
   
function Student(name,sex,school) {
  Persion.call(this,name);
  this.sex = sex;
  this.school = school;
   
  this.mySex = function () {
    return this.sex;
  }
  this.mySchool = function () {
    return this.school;
  }
}
   
var stu = new Student('前端教程网','教程','青岛市南区')
   
console.log(stu.sayHello());
console.log(stu.mySex());
console.log(stu.mySchool());

回复

我来回复
  • 暂无回复内容