"i mean if it is a property of Speak constructor all its instances should inherit it?"
No. Its instances inherit from the constructor's prototype, not the constructor itself. JavaScript is prototype-based, not "Constructor-based". If you are familiar with other OOP languages, Speak.t
will be similar to a public static property.
Changing it to Speak.protoype.t = 5
will add the property t: 5
to the prototype which will be inherited to all of its instances:
function Speak(){
show(this.t);
}
Speak.prototype.t = 5;
function show(v){
console.log('value is : '+v);
}
var s1 = new Speak(); //"value is : 5"
console.log(s1.t); //5
Since instances inherit from its constructor's prototype, you can actually achieve class inheritance by doing this:
function SpecialSpeak(){}
SpecialSpeak.prototype = new Speak();
This creates a Speak
instance and assign it as the SpecialSpeak
's prototype.
new SpecialSpeak() instanceof SpecialSpeak; //true
new SpecialSpeak() instanceof Speak; //true
Since all Speak
instances will be updated if its prototype has changed, it will also update SpecialSpeak
's prototype and also update all SpecialSpeak
's instances.
var s = new SpecialSpeak();
s.v; //undefined
Speak.prototype.v = "text";
s.v; //text
This demonstrates how inheritance works in JavaScript. The chaining of prototypes is sometimes called a "prototype chain".
You might also want to check out this great article about inheritance.
Side note: Since all prototype chains must have a starting point,
Object.prototype instanceof Object; //false
Although Object.prototype
is an object, it is the very top prototype (object) that everything* inherits from, therefore it's not an instance of Object
. It is the Object!
* Starting from ES5, Object.create
is introduced which lets you create objects that doesn't inherit from Object.prototype
.