所以我有这两个例子,来自javascript.info:
例1:
var animal = {
eat: function() {
alert( "I'm full" )
this.full = true
}
}
var rabbit = {
jump: function() { /* something */ }
}
rabbit.__proto__ = animal
rabbit.eat()
Run Code Online (Sandbox Code Playgroud)
例2:
function Hamster() { }
Hamster.prototype = {
food: [],
found: function(something) {
this.food.push(something)
}
}
// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()
speedy.found("apple")
speedy.found("orange")
alert(speedy.food.length) // 2
alert(lazy.food.length) // 2 (!??)
Run Code Online (Sandbox Code Playgroud)
从示例2开始:当代码到达时 …
无法获取以下内容以传递jslint/jshint
/*jshint strict: true */
var myModule = (function() {
"use strict";
var privVar = true,
pubVar = false;
function privFn() {
return this.test; // -> Strict violation.
}
function pubFn() {
this.test = 'public'; // -> Strict violation.
privFn.call(this); // -> Strict violation.
}
return {
pubVar: pubVar,
pubFn: pubFn
};
}());
myModule.pubFn();
Run Code Online (Sandbox Code Playgroud)
我理解它是由this函数声明中的使用引起的,但是我读过Crockford写的东西,他说违规是为了防止全局变量污染 - 但这里唯一的全局变量就是我明确定义的变量...... myModule.其他所有东西都保存在直接的功能范围内,我应该可以用它this来引用该模块.
任何想法如何让这种模式通过?
更新:如果我使用函数表达式而不是声明,这似乎工作,即
var pubFn = function () { ...
Run Code Online (Sandbox Code Playgroud)
我不是这种格式的粉丝,更喜欢将函数名称和命名参数更接近并且声明看起来/感觉更清晰.老实说,我不明白为什么这会引发违规行为 - 在这种模式中没有理由这样做.
我正在构建request模块的复合,但是我不确定在JS for Node中构建对象的最佳实践是什么.
选项1:
function RequestComposite(request) {
return {
get: function (url) { return request.get(url); }
}
}
var comp = RequestComposite(request);
Run Code Online (Sandbox Code Playgroud)
选项2:
function RequestComposite(request) {
this.request = request;
}
RequestComposite.prototype.get = function (url) { return this.request.get(url); };
var comp = new RequestComposite(request);
Run Code Online (Sandbox Code Playgroud)
选项3:
var RequestComposite = {
init: function (request) { this.request = request; },
get: function (url) { return request.get(url); }
}
var comp = Object.create(RequestComposite).init(request);
Run Code Online (Sandbox Code Playgroud)
我试图找到自己的方式,但是我对如何使用对象更加困惑...
如果我想为浏览器使用对象,答案会有所不同吗?
谢谢.