javacsript中call() 函数的认识

愚人码头 撰写  

call 方法
调用一个对象的一个方法,以另一个对象替换当前对象。

call([thisObj[,arg1[, arg2[,   [,.argN]]]]])
参数1:thisObj
可选项。将被用作当前对象的对象。
参数2:arg1, arg2, , argN
可选项。将被传递方法参数序列。
说明:
call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

看懂了没?说实话我没看懂,哈哈,没看懂继续往下看。

call 方法在js继承中经常看到,也一直搞不懂,这到底是什么东西,看下面这段代码:


function Person(name,age){
   this.name = name;
   this.age=age;
   this.alertName = function(){
    alert(this.name);
   }
   this.alertAge = function(){
    alert(this.age);
   }
  }

  function webDever(name,age,sex){
   Person.call(this,name,age);
   this.sex=sex;
   this.alertSex = function(){
    alert(this.sex);
   }
  }
  var test= new webDever("愚人码头",28,"男");
  test.alertName();//愚人码头
  test.alertAge();//28
  test.alertSex();//男

这样 webDever类就继承Person了,Person.call(this,name,age) 的 意思就是使用 Person对象代替this对象,那么 webDever中不就有Person的所有属性和方法了吗,test对象就能够直接调用Person的方法以及属性了;

说的再明白一点,就是相当于将webDever中的Person.call(this,name,age)这部分代码替换为Person类的:


this.name = name;
   this.age=age;
   this.alertName = function(){
    alert(this.name);
   }
   this.alertAge = function(){
    alert(this.age);
   }

这样webDever类就相当于:


  function webDever(name,age,sex){
   this.name = name;
   this.age=age;
   this.alertName = function(){
    alert(this.name);
   }
   this.alertAge = function(){
    alert(this.age);
   }

   this.sex=sex;
   this.alertSex = function(){
    alert(this.sex);
   }
  }
  var test= new webDever("愚人码头",28,"男");
  test.alertName();//愚人码头
  test.alertAge();//28
  test.alertSex();//男

不知道能不能这么理解?望大家斧正。

留一个问题:假设webDever类只要继承Person类中的alertName方法,这样可以吗?代码应该怎么写?

 

更多关注:理清apply, call的区别与联系

更多相关链接:


或许你对这些感兴趣:

刚刚被浏览过的文章:


3 个引用通告

  1. [...] 01.function Person(name,age){ 02. this.name = name; 03. this.age=age; 04. this.alertName = [...]

  2. [...] 函数的认识 « DLweb8|大连网页吧,您身边的建站专家. 在 javacsript中call() 函数的认识 上的评论liupeng 在 IE8的css hack [...]

  3. js中的caller和callee属性 « Javascript森林 发表在 2009年07月27日 于 2:17 下午

    [...] 另可阅读: javacsript中call() 函数的认识 [...]

发表评论

Your email is never shared. 标记为 * 的为必填项目

*
*

评论时,昵称或个人网站填的是商业网站的,一概标记为垃圾评论不予显示,并设置相关网站为过滤关键字,提交到google、百度垃圾网站数据库