我正在学习OO JavaScript,所以这个问题可能听起来很奇怪。 问题:normalize
函数应该是私有的,在外面是不可访问/可写的。 问题:如何从normalize
原型函数中访问prepare
?
var AuthHmac = AuthHmac || (function(_, CryptoJS) {
function AuthHmac(options) {
var options = options || {},
normalize = function(s) { return s.toLowerCase(); };
this.additionalHeaders = options.additionalHeaders || {};
};
AuthHmac.prototype.prepare = function(request) {
request.headers = request.headers || {};
_.each(this.additionalHeaders, function(value, name) {
request.headers[this.normalize(name)] = value;
});
};
return AuthHmac;
})(_, CryptoJS);
答案 0 :(得分:1)
不,如果normalize
函数的作用域是构造函数。
但是,由于您的函数不需要具有特权(即可以访问构造函数的局部变量),因此您可以轻松地将其放在外面,它仍然是您模块的私有函数:
var AuthHmac = AuthHmac || (function(_, CryptoJS) {
function normalize(s) { return s.toLowerCase(); }
function AuthHmac(options) {
var options = options || {};
this.additionalHeaders = options.additionalHeaders || {};
};
AuthHmac.prototype.prepare = function(request) {
request.headers = request.headers || {};
_.each(this.additionalHeaders, function(value, name) {
request.headers[normalize(name)] = value;
// ^^^^^^^^^
// No `this.`! "private attributes" in JS are variables, not properties
});
};
return AuthHmac;
})(_, CryptoJS);
答案 1 :(得分:1)
var AuthHmac = AuthHmac || (function(_, CryptoJS) {
function normalize(s) { return s.toLowerCase(); }
function AuthHmac(options) {
var options = options || {};
this.additionalHeaders = options.additionalHeaders || {};
};
AuthHmac.prototype.prepare = function(request) {
request.headers = request.headers || {};
_.each(this.additionalHeaders, function(value, name) {
request.headers[normalize(name)] = value;
});
};
return AuthHmac;
})(_, CryptoJS);
答案 2 :(得分:1)
你不能。 JavaScript没有任何私有或公共属性的概念,因此人们使用闭包和范围作为" hack"模拟隐私。但这是有代价的,即原型方法无法访问这些"私有"属性。
在您的具体示例中,normalize
也可以在构造函数之外定义,因为它不依赖于构造函数内的任何内容:
var AuthHmac = AuthHmac || (function(_, CryptoJS) {
var normalize = function(s) { return s.toLowerCase(); };
function AuthHmac(options) {
var options = options || {};
this.additionalHeaders = options.additionalHeaders || {};
};
AuthHmac.prototype.prepare = function(request) {
request.headers = request.headers || {};
_.each(this.additionalHeaders, function(value, name) {
request.headers[normalize(name)] = value;
});
};
return AuthHmac;
})(_, CryptoJS);
答案 3 :(得分:1)
将normalise
函数定义为作用域内的命名函数,而不是将其放在对象的属性中:
var AuthHmac = AuthHmac || (function(_, CryptoJS) {
function normalize(s) {
return s.toLowerCase();
}
function AuthHmac(options) {
var options = options || {};
this.additionalHeaders = options.additionalHeaders || {};
};
AuthHmac.prototype.prepare = function(request) {
request.headers = request.headers || {};
_.each(this.additionalHeaders, function(value, name) {
request.headers[normalize(name)] = value;
});
};
return AuthHmac;
})(_, CryptoJS);