原生JS中应该禁止出现的写法

2022-04-15 0 586
目录
  • 块级函数
  • 直接修改对象的 prototype 原型
  • with
  • callee
  • caller
  • eval

块级函数

严格模式下,在 ES6 之前应禁止使用。ES6 开始可以使用,函数的作用域为声明该函数的块内部。非严格模式下应禁止使用。

if(true) {
    function test() { //块级函数
        console.log(1);
    }
}
test();

直接修改对象的 prototype 原型

浏览器对原型进行了优化,在调用实例之前,会为对象的方法提前规划内存位置。所以不可以直接修改 prototype 原型。以下两种方法都应禁止使用

使用 Object.setPrototypeOf 修改原型

function a(){}
a.prototype = {
  a_prop: "a val"
};
function b(){}
var proto = {
  b_prop: "b val"
};
Object.setPrototypeOf(
  proto, a.prototype
);
b.prototype = proto;
var test = new b;
console.log(test.a_prop); // a val
console.log(test.b_prop); // b val

直接修改对象的 __proto__ 属性

function a(){}
a.prototype = {
  a_prop: "a val"
};
function b(){}
var proto = {
  b_prop: "b val",
  __proto__: a.prototype //直接修改 b 对象的 __prototype__ 属性
};
b.prototype = proto;
var test = new b;
console.log(test.a_prop); // a val
console.log(test.b_prop); // b val

with

with 的用法:

var a = {
    p1: 1,
    p2: 2
}
with (a) {
    p1 = 3;
}
console.log(a.p1);

应该禁止使用 with,例如:

function a(arg1, arg2) {
  with (arg2){
    console.log(arg1); // 无法确定是要输出第一个参数还是要输出 arg2 的 arg1 属性
  }
}
var arg2 = {arg1:1}
a("arg1", arg2)

callee

arguments.callee 表示当前正在执行的函数:

function a(arg1) {
    if (arg1 > 1) {
        return arg1 * arguments.callee(arg1 - 1);
    }
    else {
        return 1;
    }
}
console.log(a(3)); // 6

当一个函数必须调用自身的时候, 应禁止使用arguments.callee(),直接通过函数名字调用该函数。

function a(arg1) {
    if (arg1 > 1) {
        return arg1 * a(arg1 - 1); // 直接通过函数名称调用
    }
    else {
        return 1;
    }
}
console.log(a(3)); // 6

caller

caller 表示函数的调用者,应禁止使用,该特性不是标准的。

function a() {
    console.log(a.caller); // function b() { a(); }
}
function b() {
    a();
}
b();

eval

eval() 可以把传入的字符串参数当成JavaScript代码执行。

eval("var a = 1, b = 2; console.log(a+b)"); // 3

禁止使用 eval。eval 比一般JavaScript执行要慢,因为浏览器对 javascript 进行了优化。eval 方法也不安全,因为它使用与调用者相同的权限执行代码,而且 eval() 被调用时,它的作用域也会暴露。应该用 Function 代替:

var a = new Function("a", "b", "console.log(a+b)")
a(1,2); // 3

以上就是原生JS中应该禁止出现的写法的详细内容,更多关于原生JS中应该禁止的写法的资料请关注NICE源码其它相关文章!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript 原生JS中应该禁止出现的写法 https://www.niceym.com/34293.html