关于dropdown函数定义的问题点

来源:3-2 用构造函数的形式重写dropdown模块

键盘f11

2020-10-20 14:54:42

# 具体遇到的问题

http://img.mukewang.com/climg/5f8e81b409e224d007520392.jpg

http://img.mukewang.com/climg/5f8e81b4095e8b7706170157.jpg

http://img.mukewang.com/climg/5f8e81b4092a0e2607070537.jpg


# 报错信息的截图

# 相关课程内容截图

# 尝试过的解决思路和结果
想咨询一下dropdown函数的代码意义,有些理解不了
# 粘贴全部相关代码,切记添加代码注释(请勿截图)

function Dropdown($elem, options) {

        this.$elem = $elem;

            this.options = options;

        this.$layer = this.$elem.find('.dropdown-layer'),

            this.activeClass = options.active + '-active';

        this._init();

    }

 Dropdown.prototype._init=function () {

        var self=this;

        this.$layer.showHide(this.options);       

        this.$layer.on('show shown hide hidden',function (e) {

            self.$elem.trigger('dropdown-'+e.type);

            

        });


        if (this.options.event === 'click') {

            this.$elem.on('click', function(e) {

                self.show();

                e.stopPropagation();

            });

            $(document).on('click', $.proxy(this.hide, this));


        } else {

            this.$elem.hover($.proxy(this.show, this), $.proxy(this.hide, this));


        }

    }

老师,您好我想咨询一下上述的问题点:1.

this.$elem = $elem;

            this.options = options;

这个是不是实例化两个传入的参数?

 2.

this.$layer = this.$elem.find('.dropdown-layer'),

            this.activeClass = options.active + '-active';

$layer的函数定义是不是在其他的js文件中,为什么不直接function($elem,options,$layer) 直接定义三个参数,把$layer也定义进去呢? 

3.Dropdown.prototype._init=function () {}这个是属于函数的什么格式呢?老师,prototype是什么格式呢?

4.上述Dropdown.prototype._init=function () 整段代码是用干什么呢?是否可以理解点击事件的触发显示和隐藏,其中有个if,else语句,如果点击的话是显示,另外如果是鼠标划过的话也是显示的含义吗?this.$elem.hover($.proxy(this.show, this), $.proxy(this.hide, this));

写回答

1回答

好帮手慕久久

2020-10-20

同学你好,问题解答如下:

  1.   $elem、options是实例化时需要传入的参数,具体如下:

    http://img.mukewang.com/climg/5f8e8ed509d9bb7c06950241.jpg

  2. “this.$layer = this.$elem.find('.dropdown-layer')”该句代码是在实例对象上,新增一个属性$layer,因此$layer不是函数,它是属性名,它也不是在其他js文件中定义的。

    由于$layer可以利用传入的参数$elem获取到,所以无需作为参数传进来:

    http://img.mukewang.com/climg/5f8e8ffb09000d0a07580180.jpg

    如果想利用“function($elem,options,$layer)"这样的形式将$layer传进来,也不是错的,只是没必要。

  3. Dropdown.prototype._init=function () {}是在构造函数的原型对象prototype上,添加方法_init,其中prototype是构造函数Dropdown的原型对象,该种写法是面向对象编程。

    该种写法,在https://class.imooc.com/lesson/791#mid=19893章节中讲过,同学再复习一下。

  4. “Dropdown.prototype._init”这段代码的作用是初始化,即为$layer初始化showHide,为$elem绑定事件,具体如下(注意截图中注释):

    http://img.mukewang.com/climg/5f8e9227091b845109880657.jpg

    其中,“this.$elem.hover($.proxy(this.show, this), $.proxy(this.hide, this));”有两个含义,即鼠标移入时,让元素显示,移出时隐藏:

    http://img.mukewang.com/climg/5f8e928109234c9a09530145.jpg

祝学习愉快!

1

0 学习 · 14456 问题

查看课程