转自:http://blog.csdn.net/c_kite/article/details/52949885
javascript封装继承圣杯模式 和 命名空间,this,属性表示法介绍
<script>
//实现继承的方式
//1.原型链的指向
function Person() {
this.name = "peroson.name";
this.sex = "male";
this.age = 0;
}
function Student() {
}
Student.prototype = new Person();
var stu = new Student();
console.log(stu.name + " " + stu.sex + " " + stu.age); //peroson.name male 0
//2. obj.call()
function Vehicle(name, size) {
this.name = name;
this.size = size;
}
function Car(name, size, price) {
// var this =Object.create(Car.prototype);
Vehicle.call(this, name, size); // Vehicel.apply(this,price);
this.price = price;
// return this;
}
var car = new Car("MASERATI", 100, 10000);
console.log(car.name + " " + car.size + " " + car.price);
//3.共享原型
Plants.prototype.name = "xiaoliu";
function Plants(name, sex, age) {
this.name = "peroson.name";
this.sex = "male";
this.age = 0;
}
function Tree() {
}
var tree = new Tree();
Tree.prototype = Plants.prototype;
console.log("tree : " + tree.name + " " + tree.sex + " " + tree.age);
//4.圣杯模式
function Father() {
}
function Son() {
}
function inherit(Origin, Target) {
function F() { }
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;//Target的真正原型
}
Person.prototype.lastName = 'liu';
function Person() { }
function son() { }
inherit(Person, Son);
Son.prototype.age = 123;
var son = new Son;
</script>