我正在从本书的其中一个示例中练习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
};
} ());
我应该单独执行上述代码,以了解作者试图解释的概念。但是我最终在单个文件中执行了这两个代码,并且我在代码一中得到了错误消息,指出
未捕获的TypeError:未定义不是函数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
};
} ());
由于第一个代码之后缺少分号,导致出现错误,从而导致组合文件的解释方式与预期的方式完全不同。
让我们简化代码以查看结构。你有类似的东西:
getInfo = function () {
this.getYear();
}
(function () {
this.myApp = {};
} ());
在第一个函数之后没有分号,第二个函数周围的括号被视为给出调用第一个函数的参数:
getInfo = function () {
this.getYear();
}(function () {
this.myApp = {};
} ());
因此,基本上就像您写的那样:
function getInfo() {
this.getYear();
}
getInfo(function () {
this.myApp = {};
}());
this
在这两种情况下,都引用Window
(或全局对象),因为没有在实例上调用该函数。您正在调用第二个函数,该函数将set Window.myApp
,然后将其返回值(未定义)传递给getInfo
。getInfo
将访问this.getYear
不存在的内容,因此您将收到类型错误。
我在这里遇到的错误以及您的原始代码是:
TypeError:this.getYear不是一个函数
因为this
是全局对象,this.getYear
所以将是未定义的(不是函数)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句