javascript-trainning-6

//JS prototype

function A(){
this.value = 10;
this.getValue = function(){
return this.value;
};
}

var a1 = new A();
var a2 = new A();
console.log(a1.value == a2.value);
console.log(a1.getValue() == a2.getValue());
console.log(a1.getValue() === a2.getValue());
console.log(a1.getValue == a2.getValue);

function B(){
this.value = 20;
}

B.prototype.getValue = function() {
return this.value;
}

B.prototype.x=20;
var b1 = new B();
var b2 = new B();
console.log(b1.getValue == b2.getValue);
b1.x=30;
console.log(b1); //30
console.log(b2); //20

//proto. prototype

//prototype chain: b1-> B.prototype(is an Object) -> Object.prototype -> null
console.log(Object.getPrototypeOf(b1) === B.prototype);
console.log(Object.getPrototypeOf(B.prototype) ===Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype)===null);

//var B =new Function();
//prototype chain: B -> Function.prototype -> Object.prototype -> null
console.log(Object.getPrototypeOf(B) === Function.prototype);
console.log(Object.getPrototypeOf(b1))
console.log(B.prototype)

String.prototype.reverse=function(){
return this.split(‘’).reverse().join(‘’);
};

console.log(“abc”.reverse());

//Inheritance
function Parent(){
this.name=”Parent”;
}

Parent.prototype.sayHello=function(){
return “Hello, “ + this.name;
};

function child(){

}

//p -> Partent.prototype ->Object.prototype ->null
var p = new Parent();
child.prototype= p;
//c -> child.prortotype = p -> Parent.prototype -> Object.prototype ->null
var c = new child();
console.log(c.name);
console.log(c.sayHello());

// new way to do inheritance
function Base(){
this.name = “Base”; //3.{}.name =”Base”
}

Base.prototype.value =100;
function Sub(){
Base.call(this); //2.Base
//4. return {name: “Base”}
}

//sub)proto) -> Sub.prototype ={} -> Base.prototype
Sub.prototype = Object.create(Base.prototype); //{}.proto=Base.prototype;
Sub.prototype.constructor = Sub;

var sub = new Sub(); //1.{}
console.log(Base.isPrototypeOf(sub))
console.log(sub.name);
console.log(sub.value);
console.log(sub instanceof sub)