Im probably missing the point totally here so apologies. But Im wondering what the difference between using ‘this’ and ‘prototype’ are in this context. And what I should really be using to construct rich classes that are reusable…
I have this…
function MyClass() {
}
MyClass.prototype.name = null;
MyClass.prototype.init = function () {
console.log('init');
MyClass.prototype.name = 'Peter set by proto';
this.name = 'Peter set by this';
};
MyClass.prototype.SayName = function() {
console.log(MyClass.prototype.name);
console.log(this.name);
};
And on the page..
<script type="text/javascript">
var myClass = new MyClass();
myClass.init();
myClass.SayName();
</script>
The output is…
init
Peter set by proto
Peter set by this
So whats the differenve between proto and this I thought they both basically access the object/class…?
Simplly put, attribute of prototype will appear in all objects of the class, and attribute of the object just belongs to this object.
you set:
and you console.log:
all of them would show ‘Peter set by prototype’.
and if you set:
and you console.log:
would show:
Peter set by prototype
Peter set by object