JS-函数实现继承

定义一个函数来实现

    function object(o){
        function F(){}
        F.prototype = o;
        return new F();
    }
    var person = {
        name: "Nicholas",
        friends: ["Shelby", "Court", "Van"]
    };
    var anotherPerson = object(person);
    anotherPerson.name = "Greg";
    anotherPerson.friends.push("Rob");
    var yetAnotherPerson = object(person);
    yetAnotherPerson.name = "Linda";
    yetAnotherPerson.friends.push("Barbie");
    console.log(person.friends);   //"Shelby,Court,Van,Rob,Barbie"

内置的【Object.create】函数实现

    var person = {
        name: "Nicholas",
        friends: ["Shelby", "Court", "Van"]
    };
    var anotherPerson = Object.create(person);
    anotherPerson.name = "Greg";
    anotherPerson.friends.push("Rob");
    var yetAnotherPerson = Object.create(person);
    yetAnotherPerson.name = "Linda";
    yetAnotherPerson.friends.push("Barbie");
    console.log(person.friends);   //"Shelby,Court,Van,Rob,Barbie"

Object.create 的第二个参数可以是个对象,如下

    var person = {
        name: "Nicholas",
        friends: ["Shelby", "Court", "Van"]
    };
    var anotherPerson = Object.create(person, {
        name: {
            value: "Greg"
        }
    });
    alert(anotherPerson.name);  //"Greg"