【发布时间】:2014-10-07 20:56:05
【问题描述】:
我正在从书中的一个示例中练习 java 脚本并遇到以下情况
代码一:在这里我学到了 javascript 中的“this”关键字引用了拥有“this”关键字所在代码的对象。
function Vehicle1(theYear, theMake, theModel) {
var year = theYear;
var make = theMake;
var model = theModel;
this.getYear = function () { return year; };
this.getMake = function () { return make; };
this.getModel = function () { return model; };
}
Vehicle1.prototype.getInfo = function () {
return 'Vehicle1: ' + this.getYear() + ' ' + this.getMake() + ' ' + this.getModel();
}
代码二:这里我正在学习使用 IIFE(立即调用函数表达式)创建命名空间。
(function () {
this.myApp = this.myApp || {};
var ns = this.myApp;
var vehicleCount = 5;
var vehicles = new Array();
ns.Car = function () { };
ns.Truck = function () { };
var repair = {
description: 'changed spark plugs',
cost: 100
};
} ());
我应该单独执行上述代码以理解作者试图解释的概念。但我最终在单个文件中执行了这两个代码,并且我在代码一中收到错误消息说明
Uncaught TypeError: undefined is not a function Vehicle1.getInfo.myApp
问题是:IIFE 函数为何或如何尝试在代码 1 中放置或查找 myApp 命名空间?
如果我分别执行以上 2 个代码,所有代码都按预期工作。
编辑 这是完整的代码,只需使用脚本标签将其复制到 html 的头部。我在 chrome 中运行它并在控制台中查看错误详细信息
function Vehicle1(theYear, theMake, theModel) {
var year = theYear;
var make = theMake;
var model = theModel;
this.getYear = function () { return year; };
this.getMake = function () { return make; };
this.getModel = function () { return model; };
};
Vehicle1.prototype.getInfo = function () {
return 'Vehicle1: ' + this.getYear() + ' ' + this.getMake() + ' ' + this.getModel();
}
(function () {
this.myApp = this.myApp || {};
var ns = this.myApp;
var vehicleCount = 5;
var vehicles = new Array();
ns.Car = function () { };
ns.Truck = function () { };
var repair = {
description: 'changed spark plugs',
cost: 100
};
} ());
【问题讨论】:
-
“我知道'this'关键字引用了拥有'this'关键字所在代码的对象。” -- 不完全是。
this在调用函数之前什么都不是。奇迹发生在new。this将取决于您如何调用该函数。 -
您是否创建了
Vehicle1,如果是,您是否使用了new运算符?因为听起来您只是输入了Vehicle1()而不是new Vehicle1()。 -
你能发布给你这个错误的“组合”代码吗?就其本身而言,第二个 sn-p 应该没问题
-
我认为如果你在组合代码中的 sn -p 2:
;(function () {之前添加一个分号,错误将得到修复。 -
@user815923:是的,';'解决了这个问题。
标签: javascript design-patterns