JSFiddle - React, Tailwind, and code Playground
by mgibsonbr
HTML
<div id="permissivo">
<h2>Modo "permissivo"</h2>
</div>
<div id="estrito">
<h2>Modo estrito</h2>
</div>
JavaScript
function Objeto(nome) {
this.nome = nome || "obj";
}
Objeto.prototype.toString = function() { return this.nome };
var obj = new Objeto();
var foo = new Objeto("foo");
var bar = new Objeto("bar");
var vazio = { toString:function() { return ''; } };
function teste(codigo, resultado) {
$("<p><code>" + codigo + (resultado !== vazio ? ' => ' : '') + "</code></p>")
.appendTo(div)
.append("<code>" + resultado + "</code>");
}
var div = $("#permissivo");
(function() {
var f = Object.prototype.f = function() {
return "" + this + " (" + typeof this + ")";
}
teste("obj.f()", obj.f());
Number.prototype.foo = f;
teste("10.0.foo()", 10.0.foo());
teste("f.call(obj, 10, 20)", f.call(obj, 10, 20));
teste("f.call(obj, [10])", f.call(obj, [10]));
teste("f.bind(obj)()", f.bind(obj)());
teste("obj.f.call(bar)", obj.f.call(bar));
teste("f.call(20)", f.call(20));
teste("f.call(null)", f.call(null));
teste("f.call()", f.call());
teste("f()", f());
obj.bar = function() {
function g() {
return this; // this não é obj, e sim window ou undefined
// (conforme o modo, estrito ou não)
}
return g(); // Espera-se que imprima "obj", mas não é o que ocorre
}
teste("obj.bar = " + obj.bar.toString().replace(/\n/g, '<br/>').replace(/ /g, ' '), vazio);
teste("obj.bar()", obj.bar());
var x = f.bind(10); // this está amarrado a 10
teste("var x = f.bind(10);", vazio);
teste("x.call(20)", x.call(20)); // não muda o this, ainda imprime 10
})();
div = $("#estrito");
(function() {
"use strict";
var f = Object.prototype.f = function() {
return "" + this + " (" + typeof this + ")";
}
teste("obj.f()", obj.f());
Number.prototype.foo = f;
teste("10.0.foo()", 10.0.foo());
teste("f.call(obj, 10, 20)", f.call(obj, 10, 20));
teste("f.call(obj, [10])", f.call(obj, [10]));
teste("f.bind(obj)()", f.bind(obj)());
teste("obj.f.call(bar)", obj.f.call(bar));
teste("f.call(20)",...