javascript - js作用域安全的构造函数的一个问题

查看:96
本文介绍了javascript - js作用域安全的构造函数的一个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

function Polygon(sides){
                if(this instanceof Polygon){
                    this.sides=sides;
                    this.getArea=function(){
                        return 0;
                    }
                }else{
                    return new Polygon(sides);
                }
            }
            
            function  Rectangle(wifth,height){
                Polygon.call(this,2);
                this.width=this.width;
                this.height=height;
                this.getArea=function(){
                    return this.width * this.height;
                };
            }
            
            var rect=new Rectangle(5,10);
            alert(rect.sides); //undefined

这段代码是js高程三中P598-599的一个例子
我想问的是为什么alert的是undefined呢?

解决方案

开始

var rect=new Rectangle(5,10);

进入 Rectangle ,this 指向一个新 object,且叫它 object1

执行到

Polygon.call(this,2);

以 object1 的名义进入 Polygon

           function Polygon(sides){
                if(this instanceof Polygon){
                    this.sides=sides;
                    this.getArea=function(){
                        return 0;
                    }
                }else{
                    return new Polygon(sides);
                }
            }

object1 的原型是 Rectangle ,所以走到 else

return new Polygon(sides);

再次进入 Polygon ,this 指向一个新对象,且叫它为 object2

object2 的原型是 Polygon ,所以赐予 object2 sidesgetArea

回到 object1 的地盘, Polygon.call(this,2); 返回 object2 ,然后…… 然后丢掉了。

            function  Rectangle(wifth,height){
                Polygon.call(this,2);
                this.width=this.width;
                this.height=height;
                this.getArea=function(){
                    return this.width * this.height;
                };
            }

接着赐予 object1 undefinedwidthheightgetArea

最后,rect 得到了 object1

补上解决方案,让 Rectangle 共用 Polygon 的原型即可

function Rectangle(wifth,height){
    Polygon.call(this,2);
    this.width=width;
    this.height=height;
    this.getArea=function(){
        return this.width * this.height;
    };
}
Rectangle.prototype = Polygon.prototype

这篇关于javascript - js作用域安全的构造函数的一个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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