JavaScript prototype chain sample sharing
- 2020-03-30 01:28:10
- OfStack
<mce:script type="text/javascript"><!--
Function.prototype.hi = function(){alert('hi Function');}
Object.prototype.hi = function(){alert('hi Object');}
var a = function(){
this.txt = "a";
}
a.prototype = {
say:function(){alert('a');}
}
alert(a instanceof Function);//A is an instance of Function;
alert(a.__proto__ === Function.prototype);//The parent prototype of a points to the prototype of Function;
alert(Function instanceof Object);//Function is an instance of Object;
alert(Function.__proto__ === Function.prototype);//The parent prototype of Function points to the prototype of Function;
alert(Function.prototype.__proto__ === Object.prototype);//The parent of the Function stereotype points to the Object stereotype
alert(Object.__proto__ === Function.prototype);//The parent prototype of Object points to the prototype of Function;
alert(Object.prototype.__proto__);//The prototype of Object is the top of all the parent prototypes, and it no longer has a parent;
alert(a.prototype instanceof Object);//The prototype of a is also an object
alert(a.prototype.__proto__ === Object.prototype);//The parent of the prototype of a points to the prototype of Object
var A = function(){};
A.prototype = new a();
A.prototype.say = function(){
alert('A');
}
alert(A instanceof Function);//A is an instance of Function
alert(A.__proto__ === Function.prototype);//The parent prototype of A points to the prototype of Function
alert(A.prototype instanceof a);//The prototype of A is an instance of A
alert(A.prototype.__proto__ === a.prototype);//The parent of the prototype of A points to the prototype of A
var iA = new A();//IA is an instance of A,iA. S
var iB = new a();//IB is an instance of a,iB
iA.hi();
iB.hi();
a.hi();
iA.say();
iB.say();
iA.bad();
// --></mce:script>
</script>
Thanks for Simon's amendment! All instances do not look for their own prototype when they are looking for property methods (the instance's prototype is not in the prototype chain and can only be used as a property)!