gpt4 book ai didi

javascript - 将对象与模块模式组合时我做错了什么

转载 作者:行者123 更新时间:2023-11-29 18:18:20 25 4
gpt4 key购买 nike

Possible duplicate没有帮助我,因为类似的问题,我面试失败了。

想法是使用模块模式继承创建一个人对象,它是老师的父亲和经理的祖父。像经理->老师->人

我的代码看起来像这样(My Plunk):

(function(undef)
{
/**Waiting till document is ready before applying next functions*/
$(document).ready(function(){

var person = new APP.Person('Aria Stark','223232');
document.write(person.getDetails());
})();

var APP = {};

APP.Person =(function() {

function Person(name, ID) {
this.name = name;
this.ID = ID;
}

Person.prototype.getDetails = function() {
return " name: " + this.name + " ID: " + this.ID;
};

return Person;
});

APP.Teacher =(function () {

function Teacher(name, ID, salary, hatColor) {
APP.Person.call(this, name, ID);
this.salary = salary;
this.hatColor = hatColor;
}

Teacher.prototype = new APP.Person();

Teacher.prototype.getDetails = function() {
return APP.Person.call(this) + " Salary: " + this.salary + " Hat: " + this.hatColor;
};

return Teacher;
});


APP.Manager =(function () {

function Manager(name, ID, salary, hatColor, car) {
APP.Teacher.call(this, name, ID, salary, hatColor);
this.car = car;
}

Manager.prototype = new APP.Teacher();

Manager.prototype.getDetails = function() {
return APP.Teacher.call(this) + " Car: " + this.car;
};

return Manager;
});


})();

第一行出现错误:

var person = new APP.Person('Aria Stark','22323');

错误是:Uncaught TypeError: object is not a function

有人可以帮我吗?我也乐于听到对此代码的其他改进。

最佳答案

这就是您创建(和调用)self-executing function or IIFE 的方式:

(function () {})();

简单的写(function () {})并没有调用函数,在这种情况下其实没有实际作用。按照您的方式,APP.Person 将是一个函数,它返回另一个函数(Person 的构造函数)在调用时 - 它不会很好地运行使用 new

还有,对于documentready,你不想执行.ready调用的结果,直接把function作为参数传进去,它就会被调用当事件触发时:

$(document).ready(function(){
}); //removed () from here

Plunk with these changes

关于javascript - 将对象与模块模式组合时我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21111831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com