如何编写JavaScript原型链

时间:2017-08-11 05:46:14

标签: javascript oop inheritance

如何创建名为" joe"的经理对象。并创造下属" John"并将薪水添加到约翰。

实施例。 var result = new Manager(" Joe")。getSubordinate(" John")。addSalary(10000);

function Manager(name){
    this.name = name;
    this.getSubordinate = function(submane){

        return submane;
    }
}
var result = new Manager('Joe');

到目前为止我能写下来。

1 个答案:

答案 0 :(得分:0)

如果你想链接你需要的函数来返回对象,比如你有一个类经理和一个纵坐标:

function Manager(name){
    this.name = name;

    this.subordinate = {John : new Subordinate('John')};

    this.getSubordinate = function getSubordinate(subName){
        return this.subordinate[subName];
    };
}

function Subordinate(name){
    this.name = name;

    this.salary = 0;

    this.addSalary = function addSalary(salary){
        this.salary = salary;
        return salary;
    };
}

var result = new Manager('Joe').getSubordinate("John").addSalary(10000);

但我认为你想要一个Manager对象,所以我建议使用这种方式

function Manager(name){
    var self = this;

    this.name = name;

    this.subordinate = {John : new Subordinate('John')};

    this.getSubordinate = function getSubordinate(subName){
        return this.subordinate[subName];
    };

    this.addSalaryToSubordinate = function addSalaryToSubordinate(subName, salary){
        self.getSubordinate(subName).addSalary(salary);
        return self;
    };
}

function Subordinate(name){
    this.name = name;

    this.salary = 0;

    this.addSalary = function addSalary(salary){
        this.salary = salary;
        return salary;
    };
}

var result = new Manager('Joe').addSalaryToSubordinate ("John", 10000);