JS函数对象的方法
一.概述
JS中,函数是一种特殊的对象,既然是对象,那么,函数对象也想其他对象一样,可以有自己的方法,这里,主要介绍两个方法。call()方法和apply()方法
二.call()方法
function Student(name, age){
this.name = name;
this.age = age;
}
Student.prototype.sayHello = function(){
console.log("Hello, My name is " + this.name +
". I am " + this.age + " years old.");
}
var stu1 = new Student("小明", 20);
var stu2 = new Student("小红", 19);
stu1.sayHello();
stu2.sayHello.call();
stu1.sayHello.call(stu2);
第一个是我们最常见的调用,调用时,将stu1传递给sayHello()方法的this。
第二个调用调用sayHello对象的call()方法,但是并没有我们想要的结果,这里先大胆的猜测一下,等说完第三个调用第二个就明白了。
第三个调用,调用call()方法时,传递了一个参数stu2。分析结