对象方法:
num = {
next : function(){
return num.val + 1;
}
}
num.val = 1;
console.log(num.next());
个人职能:
function next(x){
return x+1;
}
num = 1;
console.log(next(num));
这些是通过对象方法和函数执行相同操作的基本示例。许多人说对象方法对模块化很有用。但我也可以用功能实现它,我的经验总是表明功能很简单,因为方法降低了存储值的灵活性。
任何人都可以举例说明对象方法如何真正有用的例子或用例,在这种情况下函数效率低下。
答案 0 :(得分:0)
如果你有两个同名的函数可以实现两个不同的东西怎么办?如果要封装私有数据和行为怎么办?
让我们看一个例子(这不是真正的代码......):
var ArrayList = function() {
var length;
var collection;
function updateLength() {
// ArrayList.length is, for whatever reason, not the same
// as collection.length
length = collection.length + 10;
}
this.add = function(element) {
collection.push(element);
updateLength();
};
this.clear = function() {
collection = [];
updateLength();
};
this.getCollection = function() {
return collection;
};
this.getLength = function() {
return length;
};
// clear the collection
this.clear();
};
var Scene = function(canvas, list) {
var context = canvas.getContext('2d');
this.draw = function() {
// do something useful with "list"
var collection = list.getCollection();
// clear the canvas
this.clear();
// for each element in the list, write it on the canvas
for (var i = 0, length = collection.length; i < length; i++)
{
context.fillText( collection[i], i*30, i*30);
}
};
this.clear = function() {
// clear the whole canvas
context.clearRect(0, 0 , canvas.width, canvas.height);
};
};
var myList = new ArrayList();
console.log(myList.getLength()); // 10
myList.add("a");
myList.add("b");
console.log(myList.getLength()); // 12
myList.clear();
console.log(myList.getLength()); // 10
// you don't have have access to those private variable outside of the object
console.log(myList.length); // undefined
console.log(myList.collection); // undefined
var canvas = document.getElementById('somecanvas');
var myScene = new Scene(canvas, myList);
myScene.draw();
myScene.clear();
// clearing all objects declared
var allObjects = [myList, myScene]
for (var i = 0, length = allObjects.length; i < length; i++)
{
allObjects[i].clear();
}
您可以在此代码中看到不同的内容:
clear
的方法,它们真的不同,我不想更改名称ArrayList
中,变量length
和collection
都是私有的,无法在对象外访问collection
中的ArrayList
中删除元素。如果变量是公开的,你就无法处理它:如果它是公开的,你就无法控制其他人用它做什么了clear
方法:它干净简单。我不必记住,对于ArrayList
类型的对象,我必须调用函数clearArrayList
,对于Scene
类型的对象,我必须调用clearScene
所有这些都是针对面向对象编程的设计(即使我的例子不是应该如此)。
它们是两种不同的编程范例:Object-oriented programming和Procedural programming。但有many more others paradigms,例如Functionnal programming