Javascript 实例属性与原型属性
在下面的代码中Javascript 实例属性与原型属性,javascript,Javascript,在下面的代码中 function Person(first, last, age) { this.firstName = first; this.lastName = last; this.age = age; } Person.prototype.planet = "Earth"; p1 = new Person("David", "Beckham", 39); p2 = new Person("Lionel", "Messi", 30); 如果使用构造函数Per
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
Person.prototype.planet = "Earth";
p1 = new Person("David", "Beckham", 39);
p2 = new Person("Lionel", "Messi", 30);
如果使用构造函数Person
创建了多个实例p1
p2
,则
我如何理解财产planet
与财产age
的区别?将属性planet
作为this.planet
添加到构造函数Person
中会有什么不同
注意:了解原型属性考虑将来我们要更改所有实例共享的原型属性时的情况
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
Person.prototype.planet = "Earth";
p1 = new Person("David", "Beckham", 39);
p2 = new Person("Lionel", "Messi", 30);
console.log(p1.planet) // Earth
Person.prototype.planet = "Mars"
console.log(p1.planet) // Mars
console.log(p1.planet === p2.planet) // true
更改prototype上的一个属性将在所有实例中更改它prototype属性将是从所谓的prototype创建的任何对象的一部分,这包括prototype链
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
}
Person.prototype.planet = "Earth";
p1 = new Person("David", "Beckham", 39);
p2 = new Person("Lionel", "Messi", 30);
console.log(p1.planet) // Earth
Person.prototype.planet = "Mars"
console.log(p1.planet) // Mars
console.log(p1.planet === p2.planet) // true
实例属性将是整个实例的一部分,在您的情况下,它将是任何实例的一部分,因为您正在构造函数中添加它:
function A() {
this.x = 11;
}
var instance = new A();
instance.x = 11;
上述两种情况都是将属性添加到自己的对象中,而不是在原型中
此外,向原型添加属性会产生副作用:
函数A(){}
A.原型x=11;
函数B(){}
B.prototype=Object.create(A.prototype);
var instanceA=newa();
var instanceB=new B();
A.原型x=12;
//两个“x”都可以容纳12个字符
警报(instanceA.x);
警报(instanceB.x)代码>这实际上是内存使用。下面是我创建的一些图像,描述了每个问题
在下图中,person的每个实例都链接到同一原型对象。如果创建指向同一对象的多个实例,这将节省内存。但是,如果将'Earth'
更改为'Mars'
,则每个实例都会有相同的更改
在下图中,每个实例将指向一个完全不同的属性,该属性专门链接到该实例。如果你相信某个特定的行星可以改变名字,你应该这样做。。否则,请使用prototype,因为这将使用更多资源
对于静态方法,您还可以使用类似于Person.planet
的语法,这样您就可以访问静态方法,而无需创建新实例。与Math.max()静态方法类似-您不需要新的Math就可以访问.max()
,我几乎不理解这句话:prototype属性将是从所谓prototype创建的任何对象的一部分,这包括prototype链。剩下的答案是重复的。目前我假设我只知道通过构造函数创建对象。@overexchange这就是为什么我将您链接到MDN,以了解有关原型链的更多信息。顺便说一句,我根据您在问题中添加的一些评论向您提供了一个更新,它总结了原型链…我开始使用MDN学习Javascript。我要强烈地说,MDN是了解原型最糟糕的资源。@overexchange如果你还在学习,你怎么能做这个大胆的陈述?这不是最糟糕的资源,而且效果很好。只是你还在学习JS,需要熟悉很多概念。我是JS新手,但对Python文档/Java JLS并不陌生。所以,我明白了,MDN有什么问题?exp&operator之类的主题在MDN中很好阅读