简体   繁体   English

与javascript原型对象混淆

[英]confusion with javascript prototype object

when we create an object like this 当我们创建这样的对象时

function Person(first,last){

this.first = first;
this.last = last;
this.full = function (){
   alert(this.first + " " + this.last); 
   }
}

obj = new Person('abdul','raziq');

could we also add to obj's prototype anything like this 我们还能将这样的东西添加到obj的原型中吗

obj.prototype = 'some functions or anything ';

or its not possible once we created the object ? 还是一旦创建对象就不可能?

and there is a __proto__ property on person object 在person对象上有一个__proto__属性

obj. OBJ。 __proto__

but when i access obj.prototype property its undefined ? 但是当我访问obj.prototype属性时,其未定义的?

can someone pls explain in a simple way possible 有人可以用简单的方式解释吗

The prototype property only exists on functions, not on instances of functions. prototype属性仅存在于函数上,而不存在于函数实例上。 Read this StackOverflow answer to know more: https://stackoverflow.com/a/8096017/783743 阅读此StackOverflow答案以了解更多信息: https : //stackoverflow.com/a/8096017/783743

You can do something like 你可以做类似的事情

Person.prototype.full = function(){
   alert(this.first + " " + this.last); 
}

Demo: Fiddle 演示: 小提琴

The prototype object is attached to the Class not to the instance so yes you can add/remove properties to/from prototype after instances are created. 原型对象是附加到Class而不是附加到实例上的,所以是的,您可以在创建实例后向原型添加属性或从原型中删除属性。 And all instances of the type will reflect the changes made. 并且该类型的所有实例将反映所做的更改。

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

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