我想从外部限制使用 JavaScript语言访问某些内容。我已经对此进行了一些研究,但是我还没有得到想要的任何东西。我知道下划线不能提供完整的保护。。当我尝试从外部接触时,很容易就能触及。我要编写示例代码。
function Car(){
this._mileage = 0;
}
Car.prototype.drive = function(miles){
if(typeof miles == 'number' && miles > 0){
this._mileage += miles;
}else{
throw new Error("Sadece pozitif sayılar girin");
}
};
Car.prototype.readMileage = function(){
return this._mileage;
}
var hondo = new Car();
console.log('old: '+hondo._mileage);
hondo._mileage = 100;
console.log('new: '+hondo._mileage);
如您所见:尽管我使用下划线,但我仍可以轻松地从教室外面访问。
我在研究中找到了一种方法。 但是我也不太明白。
var Car = (function(){
var _ = PrivateParts.createKey(); // createKey = ?
function Car(mileage){
_(this).mileage = mileage;
}
Car.prototype.drive = function(miles){
if( typeof miles == 'number' && miles > 0){
_(this).mileage += miles;
}else{
throw new Error('drive only accepts positive numbers');
}
}
Car.prototype.readMileage = function(){
return _(this).mileage;
}
return Car;
}());
答案 0 :(得分:1)
它被称为IIFE(立即调用函数表达式),这意味着用PrivateParts.createKey
制作的私钥将永远无法在函数外部访问,因为IIFE内部的代码已运行,然后结束。由于定义方式的不同,现在您有了一个完全唯一的密钥,无法从任何地方访问它。话虽这么说,在客户端执行任何密钥或加密工作仍然非常并不安全-使用PHP,Node.JS或另一种服务器端语言来完全保护您的数据。
答案 1 :(得分:1)
尽管您需要首先将privateParts
定义为您的第二条代码,但通常情况是正确的。目前看来还太复杂了。
这个想法是将变量保存在一个闭包中;由于正常的作用域规则,无法在定义变量的外部访问变量:
const fn = (() => {
const foo = 'foo';
return () => 'foo is: ' + foo;
})();
// at this point, the contents of the "foo" variable are not visible to the outside,
// you can only call the deliberately exposed function:
console.log(fn());
类似地,通过一个类,您可以将要保留为私有的所有属性保存在使用的实例索引的Map中:将Map的范围限制为该类,而不是外部的范围,您在地图上放置的所有内容都不会在外面看到:
const Car = (() => {
const map = new WeakMap();
return class Car {
constructor(mileage) {
map.set(this, { mileage });
}
drive(miles) {
if (typeof miles == 'number' && miles > 0) {
map.get(this).mileage += miles;
} else {
throw new Error('drive only accepts positive numbers');
}
}
readMileage() {
return map.get(this).mileage;
}
}
})();
var hondo = new Car(50);
console.log('old: '+hondo._mileage);
hondo._mileage = 100;
console.log('new: '+hondo._mileage);
console.log(hondo.readMileage());
hondo.drive(100);
console.log('newer: '+hondo._mileage);
console.log(hondo.readMileage());
地图基本上只是一个由每个this
(Car
的每个实例)索引的对象。因为只能在Car
闭包内部检索其值,所以这是确保信息不会暴露在外部的有效方法。
也就是说,这不会阻止客户端查看您的源代码-没有客户端代码是 truly 私有的。如果您有敏感信息,则只有他们拥有知道这些信息时,才应首先将其发送给客户端。使用这样的技术不会阻止客户端查看您的代码并可能拦截发送的信息。 (邪恶的脚本可以执行类似的操作,特别是如果有机会在脚本运行之前运行的话。)因此,该脚本实现的不是太多的 confidential ,而是它提供了合理的,但对其他行为良好的脚本如何访问数据没有严格的限制。