2015-04-13 4 views
0

Я создал двух конструкторов Person and Employee. Конструкция сотрудника, наследующая свойство Person. Это работает отлично. Теперь я хочу добавить новое свойство в конструктор Person с прототипом. Но получить пустую строку. Пожалуйста помоги.Как добавить новое свойство в существующий конструктор в качестве параметра

JS код

function Person (age, weight) { 
     this.age = age; 
     this.weight = weight; 
    } 

    Person.prototype.name = name; 

    //we will give Person the ability to share their information. 
    Person.prototype.getInfo = function() { 
     return "I am " + this.age + " year old and weight " + this.weight + " kg."; 
    }; 


    function Employee (age, weight, salary, name) { 

     //Person.call(this, age, weight); // by call parameters as arguments 
     Person.apply(this, arguments); // by apply arguments as array 
     this.salary = salary; 
    } 

    Employee.prototype = new Person(); 
    Employee.prototype.constructor = Employee; 

    Employee.prototype.getInfo = function() { 
     return "I am "+this.name+" " + this.age + " year old and weight " + this.weight + " kg having $" + this.salary +" pm salary"; 
    } 


    var person = new Employee(30, 70, 4000, "Manish"); 
    console.log(person.getInfo()); 

    document.write(person.getInfo()); 

Demo Fiddle

+0

Вы хотели сделать что-то вроде 'Person.prototype.PROPERTY = PROPERTY_VALUE'? –

+0

Да ... после этого он должен работать как «новый сотрудник» (30, 70, 4000, «Маниш») ' –

+0

Если вы это сделаете, он должен работать. Только проблема заключается в том, что значение не может быть задано динамически. И в вашем коде 'Person.prototype.name = name;' - я не думаю, что это правильно. Вы указываете на свойство 'name' на объекте' window' –

ответ

0

Вы могли бы попробовать эту реализацию:

function Person (age, weight, name) { 
    var proto = this.getProto(this); 
    this.age = age; 
    this.weight = weight; 
    if (proto) { 
     proto.name = name; 
    } 
} 

Person.prototype.getProto = function (instance) { 
    var proto; 
    if (Object.getPrototypeOf) { 
     proto = Object.getPrototypeOf(instance); 
    } else { 
     proto = instance.__proto__; 
    } 
    return proto; 
} 

//we will give Person the ability to share their information. 
Person.prototype.getInfo = function() { 
    return "I am " + this.age + " year old and weight " + this.weight + " kg."; 
}; 


function Employee (age, weight, salary, name) { 

    Person.call(this, age, weight, name); // by call parameters as arguments 
    //Person.apply(this, arguments); // by apply arguments as array 
    this.salary = salary; 
} 

Employee.prototype = Object.create(Person.prototype); 
Employee.prototype.constructor = Employee; 

Employee.prototype.getInfo = function() { 
    return "I am "+this.name+" " + this.age + " year old and weight " + 
     this.weight + " kg having $" + this.salary +" pm salary"; 
} 


var person = new Employee(30, 70, 4000, "Manish"); 
console.log(person.getInfo()); 

document.write(person.getInfo()); 

Также лучше, используя Object.create наследования вместо экземпляра более подробную информацию об этом, пожалуйста, прочитайте в answer

Более разные подходили для получения прототипа в answer

0

Я использовал ниже подход для достижения моего требования с Object.create как это было предложено Пенкрофами.

function Person() {}; 
function Employee(){}; 

// helper function for Object.create() 
Function.prototype.extends = function(superclass){ 
    this.prototype = Object.create(superclass.prototype); 
    this.prototype.constructor = this; 
} 

Employee.extends(Person); 

//Helper function for add methods in consturctor. 
Function.prototype.methods = function(name, func){ 
    this.prototype[name] = func; 
    return this; 
} 

Person 
    .methods("name", function(name){ return name; }) 
    .methods("age", function(age){ return age;}) 
    .methods("weight", function(weight){ return weight;}) 
    .methods("getPersInfo", function(age, weight){ 
     var persAge = this.age(age), 
      persWeight = this.weight(weight); 
     return "I am " + persAge + " year old and weight " + persWeight + " kg."; 
    }); 

Employee 
    .methods("salary", function(salary){return salary;}) 
    .methods("getInfo", function(name, age, weight, salary){ 
     var empAge = this.age(age), 
      empWeight = this.weight(weight), 
      empName = this.salary(name), 
      empSalary = this.salary(salary); 

     return "Empoyee name is "+empName+ " age " + empAge + " year old and weight " + empWeight + "kg. having $"+empSalary+" in hand."; 
    }); 



var person = new Person(); 
var employee = new Employee(); 

console.log(employee.getInfo("Mahesh", 30, 70, 4000)); 
document.write(employee.getInfo("Mahesh", 30, 70, 4000)); 
Смежные вопросы