gpt4 book ai didi

javascript - 构造函数中的 "use strict"是否扩展到原型(prototype)方法?

转载 作者:数据小太阳 更新时间:2023-10-29 05:22:57 25 4
gpt4 key购买 nike

我试图弄清楚“use strict”的定义是否扩展到构造函数的原型(prototype)方法。示例:

var MyNamespace = MyNamespace || {};

MyNamespace.Page = function() {

"use strict";

};

MyNamespace.Page.prototype = {

fetch : function() {

// do I need to use "use strict" here again?

}

};

根据 Mozilla您可以将其用作:

function strict(){

"use strict";

function nested() { return "And so am I!"; }

return "Hi! I'm a strict mode function! " + nested();

}

这是否意味着原型(prototype)方法从构造函数继承严格模式?

最佳答案

没有。

严格模式确实扩展到所有后代(读作:嵌套)作用域,但由于您的 fetch 函数不是在 内部 构造函数中创建的,因此它不会被继承。您需要在每个原型(prototype)方法中重复该指令。

相比之下,当构造函数处于严格模式时,特权方法将处于严格模式。为避免重复您的情况,您可以

  • a) 通过将指令移动到脚本的第一行使整个程序严格,或者
  • b) 将您的类包装在模块 IIFE 中,并使其严格:

    … = (function() {
    "use strict";

    function Page() {
    // inherits strictness
    }
    Page.prototype.fetch = function() {
    // inherits strictness
    };
    return Page;
    }());

关于javascript - 构造函数中的 "use strict"是否扩展到原型(prototype)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24035111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com