javascript - 怎么解释方法的覆盖关系?

查看:119
本文介绍了javascript - 怎么解释方法的覆盖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

http://www.cnblogs.com/yjf512/archive/2011/06/03/2071914.html#!comments
我在读这篇解释原型的博客时产生了这么个问题:

代码如图:

function baseClass()
{
    this.showMsg = function()
    {
        console.log("baseClass::showMsg");   
    }
   
    this.baseShowMsg = function()
    {
        console.log("baseClass::baseShowMsg");
    }
}
baseClass.showMsg = function()
{
    console.log("baseClass::showMsg static");
}
var baseInstance = new baseClass();
baseInstance.showMsg();    //输出baseClass::showMsg
baseClass.showMsg.call(baseClass);    //输出baseClass::showMsg static

在这里我通过call的方法来将新定义的showMsg()方法显示了出来,不过就不懂为什么产生了这种感觉会覆盖却不会覆盖的这种关系(本来想着应该都是有static的).这个和原型prototype能扯上关系吗?

想了一下确实和方法覆盖没有半毛钱关系了,因为这个例子只是凑巧名字一样,关键是类方法是一个静态方法,了解静态方法的概念就能懂了233

解决方案

function baseClass()
{
    this.showMsg = function()//[A]
    {
        console.log("baseClass::showMsg");   
    }
   
    this.baseShowMsg = function()//[B]
    {
        console.log("baseClass::baseShowMsg");
    }
}
baseClass.showMsg = function()//[C]
{
    console.log("baseClass::showMsg static");
}
var baseInstance = new baseClass();//D
baseInstance.showMsg();//[E] //输出baseClass::showMsg 
baseClass.showMsg.call(baseClass); //[F]   //输出baseClass::showMsg static

这里不存在覆盖的问题

1.函数也是对象
2.baseClass作为普通函数调用时,A处this为函数调用的上下文,可以通过函数对象的call/apply方法指定,或者不指定此时的this就是全局对象
3.baseClass通过new操作符调用时,baseClass作为一个构造函数使用,此时A处的this为通过new操作符生成的对象实例,也就是[D]中声明的baseInstance变量指向的对象
4.[E]处调用的showMsg为[A]处声明的函数对象
5.[F]baseClass.showMsg属性指向的[C]处创建的函数对象,其实在这里使不使用call方法都不影响其输出结果。

baseClass.showMsg();//输出baseClass::showMsg static

继续:

baseClass();//全局对象上将有showMsg函数和baseShowMsg
showMsg();//输出baseClass::showMsg 

接上面代码:

var myObject={
    showMsg:function()//[A]
    {
        console.log("myObject::showMsg");   
    }
}
myObject.showMsg();//输出myObject::showMsg 
baseClass.call(myObject);//全局对象上将有showMsg函数和baseShowMsg
showMsg();//输出baseClass::showMsg 
myObject.showMsg();//baseClass::showMsg 

这篇关于javascript - 怎么解释方法的覆盖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆