今天,恰好有时间,就对自己一直不是很清楚的js原型进行了一些思考和验证,所用软件为Hbuilder,不多说了,直接上代码和结果:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
在JavaScript里,任何函数都可以添加到对象上作为
对象的属性。函数的继承与其他属性继承没有差别,
包括上面的“属性覆盖”(这种情况相当于其他语言的方法
重写)
</p>
<p>
只有函数才有prototype属性
</p>
<script type="text/javascript">
var o = {
a:1,
b:2
};
//undefinded
//只有函数才有prototype属性
document.write(o.prototype+"<br />");
//undefined
window.document.write(Object.prototype.prototype+"<br />");
//[object Object]
window.document.write(Object.prototype+"<br />");
//function Empty() {}
window.document.write(Object.__proto__+"<br />");
//function Empty() {}
window.document.write(Function.prototype+"<br />");
//function Empty() {}
window.document.write(Function.__proto__+"<br />");
//false !!!
document.write((Object.__proto__ === Object.prototype)+"<br />");
//true
document.write((Function.prototype === Function.__proto__)+"<br />");
//true
document.write(o.__proto__ === Object.prototype);
document.write("<br />");
//null
document.write(o.__proto__.__proto__+"<br />");
//对o.__proto__重新赋值
o.__proto__ = {
c:3,
d:4
};
//
o.prototype = {e:5};
//[object Object]
document.write(o.prototype+"<br />");
//[object Object]
document.write(o.__proto__+"<br />");
//3
document.write(o.__proto__.c+"<br />");
//4
document.write(o.__proto__.d+"<br />");
//[object Object]
document.write(o.prototype+"<br />");
//5
document.write(o.prototype.e+"<br />");
//undefined
document.write(o.prototype.c+"<br />");
//[object Object]
document.write(o.__proto__.__proto__+"<br />");
//null
document.write(o.__proto__.__proto__.__proto__+"<br />");
//false
document.write(o.__proto__ === Object.prototype+"<br />");
document.write("<br />");
document.write('------------------------------'+'<br />');
var foo = function(){
return 111;
}
//[object Object]
document.write(foo.prototype+"<br />");
//function Empty() {}
document.write(Function.prototype+"<br />");
//function Empty() {}
document.write(foo.__proto__+"<br />");
//false
document.write((foo.prototype === Function.prototype)+"<br />");
//true
document.write((foo.__proto__ === Function.prototype)+"<br />");
//true
document.write((Function instanceof Object)+"<br />");
//true
document.write((Object instanceof Function)+"<br />");
//function Function() { [native code] }
document.write(foo.constructor+"<br />");
//function (){ return 111; }
document.write(foo.prototype.constructor+"<br />");
</script>
</body>
</html>