简体   繁体   English

在javascript中使用原型

[英]use of prototype in javascript

I am learning prototype in JavaScript and this is the code I am trying - 我正在学习JavaScript原型,这是我正在尝试的代码-

<script>
function employee(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

var trialcoder = new employee('trialcoder', 26, 'M');
//employee.prototype.salary = null;
trialcoder.salary = 19000;

document.write("salary is "+ trialcoder.salary);
</script>

My thoughts - To add another property we need to use prototype like - employee.prototype.salary = null; 我的想法 -要添加其他属性,我们需要使用prototype employee.prototype.salary = null; so on un commenting this line, I was expecting an error but it was not..let me know where I am wrong in the prototype concept. 因此,在取消对此行的评论时,我期待有一个错误,但不是。.让我知道prototype概念中的错误之处。

Code Source - http://www.w3schools.com/jsref/jsref_prototype_math.asp 代码源-http: //www.w3schools.com/jsref/jsref_prototype_math.asp

Your code is correct, because when you called 您的代码是正确的,因为当您调用

var trialcoder = new employee('trialcoder', 26, 'M');

You got an object instance of employee and just like any other object you can add properties to your trialcoder object like 您有一个employee的对象实例,就像其他任何对象一样,您可以将属性添加到trialcoder对象,例如

trialcoder.salary = 19000;

In this case, the salary property is only available to your trialcoder object and if you make another instance of employee like var another = new employee() you have no salary property in another object, but, if you do something like 在这种情况下,salary属性仅可用于您的trialcoder对象,并且如果您创建另一个employee实例,如var another = new employee() ,则another对象中将没有薪水属性,但是,如果执行类似

function employee(name, age, sex) { //... }
employee.prototype.salary = 19000;

and then make instances like 然后使像

var anEmp = new employee();
console.log(anEmp.salary); // 19000

Make another instance 制作另一个实例

var newEmp = new employee();
console.log(newEmp.salary); // 19000

if you want, you can 如果您愿意,可以

newEmp.salary = 10000;
console.log(anEmp.salary); // 10000

Which means, when you add a property in the prototype of a constructor (employee) then every object instance can share the same property and after making an instance from the constructor, you can change the property of an instance but this won't effect other instances. 这意味着,当您在构造函数(雇员)的prototype中添加属性时,每个对象实例都可以共享相同的属性,并且在从构造函数创建实例之后,可以更改实例的属性,但这不会影响其他实例。实例。 Hope it's clear enough now. 希望现在已经足够清楚了。

您的代码是正确的,并且不会收到错误,因为使用原型设置类雇员的设置属性薪金,并在创建类的对象ur后为该特定对象设置属性,如果创建另一个对象,则也可以设置其属性薪水如果使用原型设置属性,则该类的所有对象都将共享该(工资)属性。

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

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