简体   繁体   English

如何在JavaScript中创建构造函数

[英]How to create a constructor in javascript

I am trying to create a constructor in javascript. 我试图在javascript中创建一个构造函数。 This constructor is for deleteIcon. 此构造函数用于deleteIcon。 Whenever user hover any element and if i want to show a delete icon over that element than i am using this constructor. 每当用户将鼠标悬停在任何元素上时,如果我想在该元素上显示一个删除图标,那我将使用此构造函数。 But i am pretty new in this approach and i want to create a click event also in the constructor . 但是我在这种方法上还很陌生,我也想在构造函数中创建一个click事件。 Can anyone please guid me how to do this ? 谁能指导我该怎么做?

function deleteIcon(el)
{
        var self = this;
        self.button = $("<button type='button' id='removemyparent' />");

        self.element = el;

        self.add = function () {
            var widths = $(self.element).children().map(function () { return $(this).width(); });
            var maxWidth = max(widths);

            self.button.button({ text: false, icons: { primary: "ui-icon-close" } });
            $(self.element).append(self.button);

            self.button.css({ position: "absolute", top: 0, left: maxWidth - self.button.width() });
        }

        self.remove = function () {
            $(self.element).find("#" + self.button.attr("id")).remove();
        }

        self.button.click = function () {            //this is not working
            self.element.remove();
        }

 }

Try this: 尝试这个:

self.button.click(function () { self.element.remove(); })

or: 要么:

self.button.on('click', function () { self.element.remove(); })

There are few ways you can create constructor in JS. 在JS中创建构造函数的方法很少。

the most easy and clear way is this one: 最简单明了的方法是:

 // Constructor var MyObj=function(){ .... } MyObj.prototype = { constructor : MyObj, button: function(){...}, add: function(){...}, } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM