简体   繁体   English

未调用原型方法

[英]Prototype method not being called

I'm creating a custom object on click and then trying to access it's prototype's methods. 我要在单击时创建一个自定义对象,然后尝试访问它的原型方法。

$(function(){       
    $('.addtask').on("click", function(){
        var new_task = new Task();

        $('.deletetask').on("click", function(){
            new_task.deleteTask();
        });

        function Task(){        
         this.html="<li>Add Description<span class='deletetask'></span></li>";
        }

        Task.prototype = {
            constructor: Task,
            deleteTask: function(){
                this.remove()
            },
        }

    });     
});

Now when i click on class deleteTask it says: 现在,当我单击类deleteTask时,它说:

TypeError: new_task.deleteTask is not a function


new_task.deleteTask();

How can I access the prototype method deleteTask() ?? 如何访问原型方法deleteTask()?

You're setting the prototype of Task after you've created your new Task . 创建new Task 后,您将设置Task的原型。 You're not changing the prototype of your already created instances by doing so, as the prototype is referenced at the instance creation. 这样做并不是要更改已经创建的实例的原型,因为原型是在实例创建时引用的。

Move the Task.prototype = { assignation before the creation of your new Task . 在创建new Task 之前 ,将Task.prototype = {分配。

If you really want to add a function to all instances after they're created, change the prototype of the constructor instead of replacing it : 如果确实要在创建所有实例后向所有实例添加函数,请更改构造函数的原型,而不是替换它:

Task.prototype.deleteTask = function(){...

You should move the definition of Task and its prototype methods before the initial .on call. 您应该在初始.on调用之前移动Task的定义及其prototype方法。 This will incidentally fix the problem identified by @dystroy whereby you're trying to set the prototype of Task after creating an instance of it. 这将顺便解决@dystroy所标识的问题,即您在创建Task的实例后尝试设置Task的原型。

As written the Task function is recreated every time the click handler is invoked, and therefore the Task objects created on each click will be instances of different classes, which makes using the prototype moot. 如所写,每次调用单击处理程序时都会重新创建Task函数,因此,每次单击创建的Task对象将是不同类的实例,这使得使用prototype成为可能。 Prototype methods are an effective way of sharing methods amongst multiple instances, and achieving inheritance, but you're using neither. 原型方法是在多个实例之间共享方法并实现继承的有效方法,但是您都不使用。

Alternatively, leave the Task function where it is but abandon using prototype methods, eg: 或者,将Task函数保留在原处,但使用prototype方法放弃,例如:

function Task() {        
    this.html = "<li>Add Description<span class='deletetask'></span></li>";

    this.removeTask = function() {
        this.remove();
    }
}

(NB: this.remove is also undefined at this point?) (注意: this.remove还没有定义this.remove吗?)

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

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