Summary on the prototype object

Prototype prototype

  1. Every function we created, the parser will add a property to the function prototype, this property corresponds to an object that is what we call prototype object.
  2. If the function prototype as an ordinary function call has no effect.
  3. When the function is called to construct the form of a function, the object of his created will have an implicit property, pointing to the prototype object constructor, we can access the property through __proto__.
  4. Prototype object is equivalent to a public area, all instances of the same class can access to the prototype object, the object may be common to the content, unified set to the prototype object.
  5. When a property or method of access to the object, it will find itself in the first, if there is used directly, if not, to find the prototype object.
function MyClass() {
	
}
// 向MyClass的原型中添加属性a
MyClass.prototype.a = 123;
// 向MyClass的原型中添加方法 fun,同理
MyClass.prototype.sayName = function fun() {
	alert('123');
};
var mc = new MyClass();
console.log(MyClass.prototype);
console.log(mc.__proto__);
console.log(mc.__proto__ == MyClass.prototype); // true
console.log(mc.a)
  1. When you create a constructor later, these objects can be shared properties and methods, unity added to the prototype object constructor, so do not separately for each object is added, it will not affect the global scope, you can make each object We have these properties and methods of.
  2. When use in checking whether the object contains a property, but if the object does not have a prototype, will return true. Whether the object can be used hasOwnProperty () to check the object containing the attribute itself.
console.log("a" in mc)
console.log(mc.hasOwnProperty(“a”));

Prototype object is an object, so it also has a prototype.
When a property or method of an object, will now find itself, itself have the direct use, not to go looking for the prototype object, if you use the prototype object, if it is not the prototype to prototype objects in Look for. Until you find the Object prototype object. Object prototype object is not a prototype, if still not found in Object, undefined is returned.

// hasOwnProperty在原型的原型里
console.log(mc.__proto__.__proto.__.hasOwnProperty("hasOwnProperty");
Published 27 original articles · won praise 4 · Views 2821

Guess you like

Origin blog.csdn.net/qq_39083496/article/details/102775231