百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> 详细介绍prototype与__proto__的区别
分享文章到:

详细介绍prototype与__proto__的区别

发布时间:01/15 来源: 浏览: 关键词:
小编推荐的这篇文章详细介绍prototype与__proto__的区别,非常有用,有兴趣的同学可以参考一下

prototype与__proto__区别

Each constructor is a function that has a property named “prototype” that is used to implement prototype-based inheritance and shared properties. Every object created by a constructor has an implicit reference (called the object's prototype) to the value of its constructor's “prototype” property.
When a constructor creates an object, that object implicitly references the constructor's prototype property for the purpose of resolving property references. The constructor's prototype property can be referenced by the program expression constructor.prototype, and properties added to an object's prototype are shared, through inheritance, by all objects sharing the prototype. Alternatively, a new object may be created with an explicitly specified prototype by using the Object.create built-in function. –ECMAScript® 2015 Language Specification

__proto__是每个对象都有的一个属性,而prototype是函数才会有的属性!!!

使用Object.getPrototypeOf()代替__proto__!!!

一、prototype

几乎所有的函数(除了一些内建函数)都有一个名为prototype(原型)的属性,这个属性是一个指针,指向一个对象,而这个对象的用途是包含可以有特定类型的所有实例共享的属性和方法。prototype是通过调用构造函数而创建的那个对象实例的原型对象。hasOwnProperty()判断指定属性是否为自有属性;in操作符对原型属性和自有属性都返回true。

示例:自有属性&原型属性

varobj = {a: 1};
obj.hasOwnProperty("a");// true
obj.hasOwnProperty("toString");// false
"a"inobj;// true
"toString"inobj;// true

示例:鉴别原型属性

functionhasPrototypeProperty(obj, name){
  returnnameinobj && !obj.hasOwnProperty(name);
}

二、__proto__

对象具有属性__proto__,可称为隐式原型,一个对象的隐式原型指向构造该对象的构造函数的原型,这也保证了实例能够访问在构造函数原型中定义的属性和方法。

functionFoo(){}
varBoo = {name:"Boo"};
Foo.prototype = Boo;
varf =newFoo();
 
console.log(f.__proto__ === Foo.prototype);// true
console.log(f.__proto__ === Boo); // true
Object.getPrototypeOf(f) === f.__proto__; // true

三、Object.getPrototypeOf()

一个对象实例通过内部属性[[Prototype]]跟踪其原型对象。使用原型对象的好处是可以让所有对象实例共享它所包含的属性和方法。可以调用对象的Object.getPrototypeOf()方法读取[[Prototype]]属性的值,也可以使用isPrototypeOf()方法检查某个对象是否是另一个对象的原型对象。大部分JavaScript引擎在所有对象上都支持一个名为__proto__的属性,该属性可以直接读写[[Prototype]]属性。

示例:原型对象

functionPerson(name) {
  this.name = name;
}
Person.prototype = {
  constructor: Person,
  sayName:function(){
    console.log("my name is "+this.name);
  }
}
varp1 =newPerson("ligang");
varp2 =newPerson("Camile");
p1.sayName(); // my name is ligang
p2.sayName(); // my name is Camile

While Object.prototype.proto is supported today in most browsers, its existence and exact behavior has only been standardized in the ECMAScript 6 specification as a legacy feature to ensure compatibility for web browsers. For better support, it is recommended that only Object.getPrototypeOf() be used instead. –MDN

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有4人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板