我是JavaScript的新手,但我对闭包的工作原理感到困惑.有人可以用非专业人的术语解释它们是什么或为什么它们有用吗?
如果我可以obj.constructor.prototype用来访问对象的原型,那么为什么我不能obj.constructor.prototype.constructor.prototype用来遍历原型链并且必须使用Object.getPrototypeOf?
function MyConstructor()
{
this.prop = 1;
}
var o = new MyConstructor();
console.log(o.constructor.prototype) // MyConstructor
console.log(o.constructor.prototype.constructor.prototype) // MyConstructor?
Run Code Online (Sandbox Code Playgroud)
它不应该返回MyConstructor的原型function() { [native code] }(在Chrome控制台中)吗?
所以我想弄清楚这个难题:
function fun1(){
var result = [];
for (var i = 0; i < 5; i++){
result.push( function() {return i} );
}
return result;
}
console.log(fun1()[0]()) // returns 5?
Run Code Online (Sandbox Code Playgroud)
不应该该数组的第一个元素返回一个返回'0'的函数?
如果我声明一个函数文字:
var x = function(){
alert('hi');
};
console.log(x); // returns the function code.
Run Code Online (Sandbox Code Playgroud)
然而:
var x = (function(){
alert('hi');
})();
console.log(x); // returns undefined?
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会这样.将函数编写为文字是不是仍然能够通过其变量引用名称来访问它?我知道这可能很傻,但我只是在学习javascript,所以不要过于严厉地判断.
我真的很困惑JavaScript中存在的不同属性,用于获取文档的尺寸以及如何获取这些数字.有人可以推荐一个好地方开始了解我如何获得文档的大小和正确定位的东西?
愚蠢的问题,但是当我写作时,window.onload = alert('hi')我得到警报.
但是,如果我测试它的存在:if (window.onload) alert("exists")我得到undefined.怎么会?
javascript ×7
closures ×1
constructor ×1
dimensions ×1
document ×1
function ×1
jquery ×1
position ×1
prototype ×1
scope ×1
scrollbars ×1
variables ×1