this vs prototype Javascript
This question already has an answer here:
I'm going to try to guess/address your actual concerns.
See the following code snippet:
function A() {
this.text = "hello";
}
var a = new A();
a.text = "hello world";
Actually there's only a difference between setting text
property inside the constructor (ie this.text
) function or once the object has been already created (ie a.text
). Basically, this
within the constructor function is the object being created and a
variable is the object already created.
The only difference between the two is that a property defined in the object being created during the call to the constructor function will be created to all objects creared by the whole constructor function.
Now see the following code snippet too:
function A() {}
A.prototype = {
text: "hello"
};
var a1 = new A();
var a2 = new A();
// both will output "hello"
console.log(a1.text);
console.log(a2.text);
A.prototype.value = "bye";
// both will output "bye"
console.log(a1.text);
console.log(a2.text);
Conclusion: properties defined in the prototype of a constructor function are shared by all objects sharing the same prototype. Thus, they're alive even if you create objects using the constructor function or not.
链接地址: http://www.djcxy.com/p/30094.html上一篇: 如何删除基于键的数组元素?
下一篇: 这与原型Javascript