Это самый простой пример объекта JS, о котором я могу думать, который иллюстрирует мои вопросы.Javascript OOP - объявление методов объекта
Вопрос 1.
Как я могу ссылаться на функцию в классе, так что в другом коде, который я мог бы вызвать метод? Это дает мне ошибку.
var name1 = new Name();
name1.render();
Вопрос 2.
чем разница между объявлением функций в линии, как эти против использования var getByID = function() ...
?
Пример объекта:
function Name(user_id, container_id) {
this.userID = user_id;
this.containerID = container_id;
this.firstName = null;
this.lastName = null;
function getByID(userID) {
// An ajax call that takes a userID to get a name.
}
function setName() {
// An ajax call to get the name from db.
name_record = this.getByID(this.userID); ????? this returns an error that getByID is undefined.
this.firstName = name_record.firstName;
this.lastName = name_record.lastName;
}
function render() {
$(this.containerID).val(this.firstName + ' ' + this.lastName);
}
}
Вам нужно передать некоторые параметры в 'Name'. 'container_id'' undefined', поэтому '$ (this.containerID)' не будет работать. –
Связанный: http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript – cmbuckley
Вопрос 2: http://stackoverflow.com/questions/336859/var-functionname-function- vs-function-functionname – orhanhenrik