I'm trying to figure out whether the definition of 'use strict' extends to the prototype methods of the constructor. Example:
var MyNamespace = MyNamespace || {};
MyNamespace.Page = function() {
"use strict";
};
MyNamespace.Page.prototype = {
fetch : function() {
// do I need to use "use strict" here again?
}
};
According to Mozilla you can use it as:
function strict(){
"use strict";
function nested() { return "And so am I!"; }
return "Hi! I'm a strict mode function! " + nested();
}
Does it mean that prototype methods inherit strict mode from the constructor?
The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables. The numbers in the table specify the first browser version that fully supports the directive. You can use strict mode in all your programs.
Benefits of using “use strict” It changes previously accepted "bad syntax" into real errors. As an example, mistyping a variable name creates a new global variable. When using strict mode, this will throw an error. It leads to making it impossible to accidentally create a global variable.
Every constructor has a prototype property, which will become the instance's [[Prototype]] when called via the new operator.
So what's the difference between constructor and prototype? A short answer is that the constructor is a function that is used to create an object, while the prototype is an object that contains properties and methods that are inherited by objects created from a constructor.
No.
Strict mode does extend to all descendant (read: nested) scopes, but since your fetch
function is not created inside the constructor it is not inherited. You would need to repeat the directive in each of the prototype methods.
Privileged methods in contrast would be in strict mode when the constructor is in strict mode. To avoid repetition in your case, you can
b) wrap your class in a module IIFE, and make that strict:
… = (function() {
"use strict";
function Page() {
// inherits strictness
}
Page.prototype.fetch = function() {
// inherits strictness
};
return Page;
}());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With