gpt4 book ai didi

javascript - 什么时候使用 "prototype"这个词来为 javascript 中的对象添加新属性?

转载 作者:可可西里 更新时间:2023-11-01 02:20:03 24 4
gpt4 key购买 nike

我不明白在 JavaScript 中什么时候使用“原型(prototype)”这个词,什么时候使用简单的“点”符号而不使用“原型(prototype)”这个词。有人可以查看这些代码块并帮助我了解您何时想要使用一个代码块吗?

“原型(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);

没有“原型(prototype)”:

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 对象有一个属性,它是指向另一个对象的指针。这个指针是对象的原型(prototype)。默认情况下,对象实例共享相同的原型(prototype):

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

关于javascript - 什么时候使用 "prototype"这个词来为 javascript 中的对象添加新属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10430794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com