2017-01-29 9 views
0

У меня есть объект, называемый сотрудником с его получателями и сеттерами, будут ли они четко определены и реализованы?Как вызвать и создать объект в Javascript?

Как я могу получить доступ к значениям объекта Person в моей функции Список Javascript, чтобы я мог показать его в моей динамической таблице?

var operations = { 

    init: function() { 
     console.log("init"); 
     operations.setupButton(); 
    }, 
    setupButton: function() { 
     $("#btnList").on("click", operations.list); 
    }, 
    list: function() { 

     var table = $("#tblEmployee"); 
     var strHtml = ""; 


     var emp = new employee(); 
     // load my jsp table 
     strHtml += '<tr>'; 

     strHtml += '<td>' + emp.getName + '</td>'; 
     strHtml += '<td>' + emp.getAge + '</td>'; 
     strHtml += '<td>' + emp.getSalary + '</td>'; 

     strHtml += '<tr>'; 

     tabla.append(strHtml); 
    } 
}; 

var employee = { 

    name: 'Jean', 
    age: 22, 
    salary: 8000000, 

    getName() { 
     return this.name; 
    }, 
    getAge() { 
     return this.age; 
    }, 
    getSalary() { 
     return this.salary; 
    } 
}; 
$(document).ready(operations.init); 

ответ

0

Я немного изменил ваш код. Я не уверен, что это то, что вам нужно. Проверьте его и при необходимости обновите jsFiddle.

example code in JsFiddle

function employee() { 
    this.name = 'Jean'; 
    this.age = 22; 
    this.salary = 8000000; 

    this.getName = function() { 
     return this.name; 
    } 
}; 

var operations = { 
    init: function() { 
     console.log("init"); 
     operations.setupButton(); 
    }, 
    list: function() { 
     var table = $("#tblEmployee"); 
     var strHtml = ""; 
     var emp = new employee(); 
     strHtml += '<tr>'; 
     strHtml += '<td>' + emp.getName() + '</td>'; 
     strHtml += '</tr>'; 
     table.append(strHtml); 
    }, 
    setupButton: function() { 
     $("#btnList").on("click", operations.list); 
    }  
}; 

$(document).ready(operations.init); 
-1

У вас есть несколько опечаток и сделать что-то неправильно

function Employee(){ 
 

 
    name = 'Jean'; 
 
    age = 22; 
 
    salary: 8000000; 
 

 
    getName = function() { 
 
     return this.name; 
 
    } 
 
    
 
    getAge = function() { 
 
     return this.age; 
 
    } 
 
    
 
    getSalary = function() { 
 
     return this.salary; 
 
    } 
 
}; 
 

 
var operations = { 
 

 
    init: function() { 
 
     console.log("init"); 
 
     operations.setupButton(); 
 
    }, 
 
    setupButton: function() { 
 
     $("#btnList").on("click", operations.list); 
 
    }, 
 
    list: function() { 
 

 
     var table = $("#tblEmployee"); 
 
     var strHtml = ""; 
 

 

 
     var emp = new Employee(); 
 
     // load my jsp table 
 
     strHtml += '<tr>'; 
 

 
     strHtml += '<td>' + emp.getName + '</td>'; 
 
     strHtml += '<td>' + emp.getAge + '</td>'; 
 
     strHtml += '<td>' + emp.getSalary + '</td>'; 
 

 
     strHtml += '<tr>'; 
 

 
     table.append(strHtml); 
 
    } 
 
}; 
 

 
$(document).ready(operations.init);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<table id="tblEmployee"> 
 
    <tbody> 
 
    </tbody> 
 
</table> 
 
<button id="btnList">List</button>

Проверьте вас ошибки здесь:

Javascript "Not a Constructor" Exception while creating objects

+0

Вы создаете глобалам –

0

Существует два способа представить Employee, в зависимости от того, какая версия ECMAScript вы можете предположить.

ES6 или выше, вы можете написать класс. (Это действительно синтаксический сахар над тем, как ES5, который я покрою после)

class Employee { 
    constructor(name = 'Jean', age = 22, salary = 8000000) { // ES6 supports param defaults 
     Object.assign(this, { 
      name, 
      age, 
      salary 
     }); 
    } 
    // These functions will be inherited by and shared by all instances of Employee 
    getName() { 
     return this.name; 
    } 
    getAge() { 
     return this.age; 
    } 
    getSalary() { 
     return this.salary; 
    } 
} 

ES5 или ниже, с помощью функции конструкторы и прототипичного наследование. Это более верно, как JavaScript действительно реализует структуру

function Employee(name, age, salary) { 
    if (typeof name === 'undefined') name = 'Jean'; // ES5 requires manual default setting 
    if (typeof age === 'undefined') age = 22; 
    if (typeof salary === 'undefined') salary = 8000000; 
    this.name = name; 
    this.age = age; 
    this.salary = 8000000; 
} 
// These functions will be inherited by and shared by all instances of Employee 
Employee.prototype.getName = function getName() { 
    return this.name; 
}; 
Employee.prototype.getAge = function getAge() { 
    return this.age; 
}; 
Employee.prototype.getSalary = function getSalary() { 
    return this.salary; 
}; 

Использование в обоих случаях

new Employee(); // Employee {name: 'Jean', age: 22, salary: 8000000} 

 Смежные вопросы

  • Нет связанных вопросов^_^