简体   繁体   English

以下两个声明之间的区别是什么以及何时应该使用它们

[英]What is the difference between the following two declarations and when should they be used

I am learning javascript. 我正在学习javascript。 I am confused between the following two notations where the newly created objects inherit the properties. 我在以下两个表示法中感到困惑,其中新创建的对象继承了属性。 How are they different and when should i use them? 它们有何不同,何时使用它们?

Code 1: 代码1:

 var Vehicle = function Vehicle() {
       this.wheel=2
    }

    var vehicle = new Vehicle();
    alert(vehicle.wheel);

Code 2: 代码2:

 var Vehicle = function Vehicle() {
    }
    Vehicle.prototype.wheel = 4;
    var vehicle = new Vehicle();
    alert(vehicle.wheel);

When is the keyword prototype used? 什么时候使用关键字prototype

Properties defined on prototype will be shared by all the instances. 原型上定义的属性将由所有实例共享。 So if you create 10 vehicles, they just share the wheel property(only one), and each vehicle doesn't have a wheel property on itself . 所以,如果你创建10辆,他们只是共享轮属性(只有一个),每个车辆不会 对自己的车轮财产。

最重要的区别是,当您向函数原型添加属性并从中实例化新对象时,通过加强继承链而不是直接在对象上来访问新对象中的属性。

You need to read about prototype, there were lots of threads in stackoverflow, do a little search. 你需要阅读原型,stackoverflow中有很多线程,做一点搜索。 For example read this article . 例如,阅读这篇文章 Or grab a book which is the best approach to learn something, I recommend this great book, JavaScript: The Good Parts 或者拿一本书是最好的学习方法,我推荐这本好书,JavaScript: The Good Parts

In general it's much better using prototype in terms of memory consumption and prototype chain that can be extendable. 一般而言,在内存消耗和可扩展的原型链方面使用原型要好得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM