我做了兩個類,即人 - 父類和學生類 - 子類。我正在嘗試實現繼承。我也試圖在模塊化模式下實現它。但它沒有得到妥善處理。對於代碼塊請在下面檢查。將參數傳遞給JavaScript模塊化模式中的父類
Person.js
var Person = function() {
var details, constructor, getDetailsByAttribute, setDetailsByAttribute, setDetails, getDetails, clearDetails;
clearDetails = function() {
details = {
uid : '',
name : '',
email : ''
};
};
getDetailsByAttribute = function(attr) {
return details[attr];
};
setDetailsByAttribute = function(key, value) {
if(details.hasOwnProperty(key)) {
details[key] = value;
}else {
console.log('invalid key');
}
};
setDetails = function(param) {
clearDetails();
for(var attr in param) {
if(details.hasOwnProperty(attr)) {
details[attr] = param[attr];
}
}
};
getDetails = function() {
return details;
};
/**
* During object creation;
*/
if(arguments.length >= 1) {
//clearDetails();
setDetails(arguments[0]);
}
return {
getDetailsByAttribute : function(attr) {
return getDetailsByAttribute(attr);
},
setDetailsByAttribute : function(key, value) {
setDetailsByAttribute(key, value);
},
setDetails : function(params) {
setDetails(params);
},
getDetails : function() {
return getDetails();
},
clearDetails : function() {
clearDetails();
}
};
};
Student.js
var Student = function() {
Person.call(this,arguments);
};
Student.prototype = new Person();
的index.html
<html>
<head>
</head>
<body>
<script type="text/javascript" src="modules/Person.js"></script>
<script type="text/javascript" src="modules/Student.js"></script>
<script type="text/javascript">
var person1, person2, person3, student1;
person1 = new Person({
uid : 5225,
name : 'jaison',
email : '[email protected]'
});
person2 = new Person({
uid : 5222,
name : 'jatin',
email : '[email protected]'
});
person3 = new Person();
person3.setDetails({
uid : 5221,
name : 'sarath',
email : '[email protected]'
});
person3.setDetailsByAttribute('name', 'sarath');
student1 = new Student({
uid : 5221,
name : 'sachin',
email : '[email protected]'
});
console.log('person 1 : ',person1.getDetails());
console.log('person 2 : ',person2.getDetails());
console.log('person 3 : ',person3.getDetails());
console.log('student 1 : ',student1.getDetails());
//console.log(student1.get);
</script>
</body>
</html>
可能重複[如何獲得構造函數從JavaScript中的構造函數繼承?](http://stackoverflow.com/questions/2263353/how-to-get-a-constructor-function-to-繼承一個構造函數在java中) – outis
一個簡單地調用另一個函數的匿名函數(比如你在由'Person'構造函數返回的對象文字中使用)是完全沒有必要的。只需使用該功能即可。 '{getDetailsByAttribute:getDetailsByAttribute,...}'是完全合法的,並且工作正常,因爲對象的屬性是與其他對象屬性和本地變量不同的命名空間。 – outis
感謝您的寶貴意見。但是參考上面提到的問題,我改變了一些代碼,但仍然不起作用。 –