javascript的call()如何继承prototype的方法?

新手上路,请多包涵

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
    /*第一组*/
    .btn button{}
    .btn button.active{ background: #f00; }
    .obox li{ display: none; }
    .obox li.active{ display: block; }
    /*继承出来的*/
    .btns button{}
    .btns button.active{ background: #f00; }
    .oboxs li{ display: none; }
    .oboxs li.active{ display: block; }
</style>

</head>
<body>

<!-- 第一组 -->
<div class="btn">
    <button type="button" class="active">按钮1</button>
    <button type="button">按钮2</button>
    <button type="button">按钮2</button>
</div>
<div class="obox">
    <ul>
        <li class="active">内容1</li>
        <li>内容2</li>
        <li>内容3</li>
    </ul>
</div>
<!-- 继承出来的 -->
<div class="btns">
    <button type="button" class="active">按钮1</button>
    <button type="button">按钮2</button>
    <button type="button">按钮2</button>
</div>
<div class="oboxs">
    <ul>
        <li class="active">内容1</li>
        <li>内容2</li>
        <li>内容3</li>
    </ul>
</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="tab.js"></script><!-- 外部引入插件 -->
<script type="text/javascript" src="limitTab.js"></script><!-- 再继承一次tab的方法 -->
<script type="text/javascript">
    $(function(){
        new Tab(".btn",".obox");
        new LimitTab(".btns",".oboxs");
    })
</script>

</body>
</html>

自己写的tab.js(prototype继承相关)

function Tab(btnName,boxName) {

    this.btnName = btnName;    
    this.boxName = boxName;
    // console.log(this)
    this.myMethods();                    

}
Tab.prototype.myMethods = function(){

var _this = this;
$(this.btnName+" button").each(function(index){
    $(this).click(function(){
        $(this).addClass("active").siblings().removeClass("active");
        $(_this.boxName+" li").eq(index).addClass("active").siblings().removeClass("active");
    })
})

}

limitTab.js(call()方法相关)

// console.log(Tab.prototype)
function LimitTab(btnName,boxName) {

Tab.call(this,btnName,boxName);//继承原来tab插件的属性和方法,call

}
for (var i = 0; i < Tab.prototype.length; i++) {

LimitTab.prototype[i]=Tab.prototype[i];

}

问题:当limitTab.js里用call()方法去继承tab.js里的tab属性和方法时,发现this.myMethods();这个方法死活继承不上,会报错,求教如何能让limitTab.js用call()方法继承到tab.js里的this.myMethods()方法呢?谢谢

阅读 1.4k
1 个回答
function Tab(btnName,boxName) {
    ...                 
}
Tab.prototype.myMethods = function(){
    ...
}

function LimitTab(btnName,boxName) {
    Tab.call(this,btnName,boxName); // 对象冒充继承,这是实例化的子类传值给父类,并不能继承原形链上的方法
}
LimitTab.prototype = Tab.prototype; // 继承原形链
// LimitTab.prototype = new Tab(); // 或者这么写

var aaa = new LimitTab('123', 'abc');
aaa.myMethods();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题