prototype、js中的三种方法、call

javascript的方法可以分为三类:

a 类方法
b 对象方法
c 原型方法

   function Person(name) {
         this.name=name;
        //对象的方法
        this.sayName=function () {
             console.log(name)
        }
    }
    //类的方法
    Person.Run=function () {
          console.log("人正在跑");
    }
    //原型的方法
    Person.prototype.sayChina=function () {
        console.log("我的名字是"+this.name);
    }
    var cc=new Person("ssa");
    //对象的方法只能通过对象来调用
     cc.sayName();
    //类的方法只能通过类来调用
    Person.Run();
    //原型的方法通过对象来调用
    cc.sayChina();

函数的call()方法

语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定义:调用一个对象的一个方法,以另一个对象替换当前对象。

function add(a,b)  
{  
    alert(a+b);  
}  
function sub(a,b)  
{  
    alert(a-b);  
}  

add.call(sub,3,1);   

会输出4
这个例子中的意思就是用 add 来替换 sub,add.call(sub,3,1) == add(3,1) ,所以运行结果为:alert(4);

  function Animal(){
        this.name = "Animal";
        this.showName = function(){
            alert(this.name);
        }
    }
    function Cat(){
        this.name = "Cat";
    }
    var animal = new Animal();
    var cat = new Cat();
    //通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。
    //输入结果为"Cat"   
    animal.showName.call(cat,",");

call 的意思是把 animal 的方法放到cat上执行,原来cat是没有showName() 方法,现在是把animal 的showName()方法放到 cat上来执行,所以this.name 应该是 Cat
animal是提供方法的,cat是提供实例的。

prototype

原型的工作方式:当你构造一个对象的新实力的时候,定义在对象的原型中的所有属性和方法,在运行的时候都会附着在新的实例上。

 function newClass() {
     this.firstName="frank";
 }
    newClass.prototype.say=function () {
        console.log(this.firstName);
    }
    var cc=new newClass();
    cc.say();

A.prototype = new B();
理解prototype不应把它和继承混淆。A的prototype为B的一个实例,可以理解A将B中的方法和属性全部克隆了一遍。A能使用B的方法和属性。这里强调的是克隆而不是继承。可以出现这种情况:A的prototype是B的实例,同时B的prototype也是A的实例。

 function baseClass()
    {
        this.showMsg = function()
        {
            console.log("baseClass::showMsg");
        }
    }
    function extendClass()
    {
    }
    extendClass.prototype = new baseClass();
    var instance = new extendClass();
    instance.showMsg(); // 显示baseClass::showMsg

子类会继承父类所有的方法


父类使用子类的同名的方法 call方法的实现

  function baseClass()
    {
        this.showMsg = function()
        {
            console.log("baseClass::showMsg");
        }
    }
    function extendClass()
    {
        this.showMsg =function ()
        {
            console.log("extendClass::showMsg");
        }
    }
    extendClass.prototype = new baseClass();
    var Einstance = new extendClass();
    var BInstance=new baseClass();
      BInstance.showMsg.call(Einstance)  //Extend类的实例调用了Base类的方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值