我在
JavaScript中不明白什么时候使用单词“prototype”,而不使用简单的“dot”符号而没有单词“prototype”.有人可以看这些代码块,并帮助我了解什么时候想要使用另一个?
与“原型”:
function employee(name,jobtitle) { this.name=name; this.jobtitle=jobtitle; } var fred=new employee("Fred Flintstone","Caveman"); employee.prototype.salary=null; fred.salary=20000; console.log(fred.salary);
没有“原型”:
function employee(name,jobtitle,salary) { this.name=name; this.jobtitle=jobtitle; this.salary=salary; } var fred=new employee("Fred Flintstone","Caveman",20000); console.log(fred.salary);
解决方法
JavaScript对象具有指向另一个对象的指针的属性.这个指针是对象的原型.对象实例默认共享相同的原型:
function Employee(name){ this.name = name; } Employee.prototype.company = "IBM"; Employee.prototype.who = function(){ console.log("My name is",this.name,"I work for",this.company); } var bob = new Employee('Bob'); var jim = new Employee('Jim'); // bob and jim are seperate objects,but each is linked to the same 'prototype' object. jim.who(); // jim doesn't have a property called 'who',so it falls back to it's 'prototype',where who exists // My name is Jim I work for IBM bob.who(); // My name is Bob I work for IBM // Bob leaves IBM for Microsoft bob.company = "Microsoft"; // bob now has a property called 'company'. The value of which is 'Microsoft',which overrides bob's prototype property of the same name. bob.who(); // My name is Bob I work for Microsoft Employee.prototype.company = 'Facebook'; jim.who(); // My name is Jim I work for Facebook bob.who(); // Bob is not affected by the change. // My name is Bob I work for Microsoft delete bob.company; bob.who(); // bob no longer has it's own property 'company',so like jim,it drops down to the prototype object. // My name is Bob I work for Facebook