js函数定义方式为什么可以这样写

Jack0801 2012-06-19 05:16:18
最近在看HighCharts这个生成图表的js插件,纯js做的,看到里面有很多函数都是这样定义的,如:函数名:function(参数){函数体},为什么可以这样定义,这种定义方式和:function 函数名(参数){函数体}这种定义方式有什么区别吗?那位能解答一下,不胜感激!
...全文
116 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
加了一些注释,或许你能更好地理解:

<script type="text/javascript">

// 声明一个 Student 的类,同时有个构造方法
// 当然,也可以写成这样:
/*
function Student(name) {
this.name = name;
}
*/
var Student = function(name) {
this.name = name;
};

// 给 Student 上添加一个 getName 函数
// 注意这个与这个的区别:
/*
// 这种相当于 Java 中的静态方法
Student.getName = function() {
return 'name';
}
*/
// 这种相当于 Java 中的类方法
Student.prototype.getName = function() {
return this.name;
};

Student.prototype.setName = function(name) {
this.name = name;
};

Student.prototype.toString = function() {
return 'name: ' + this.name;
};

window.onload = function() {
var student = new Student('tom');
alert(student.getName());
alert(student.toString());
}

</script>
  • 打赏
  • 举报
回复
放在 prototype 中只能用“:”,如果想用“=”的话等这样写:

<script type="text/javascript">

var Student = function(name) {
this.name = name;
};

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

Student.prototype.setName = function(name) {
this.name = name;
};

Student.prototype.toString = function() {
return 'name: ' + this.name;
};

window.onload = function() {
var student = new Student('tom');
alert(student.getName());
alert(student.toString());
}

</script>


JavaScript 中的东西对于经常使用 Java 的人来说很难理解,主要要弄清楚这些在 Java 中不存在的概念:

闭包、原型链、可变的 this 对象、函数即是类、弱类型对象
Jack0801 2012-06-19
  • 打赏
  • 举报
回复
是的,是放在prototype中,像这样两种函数的定义方式在作用上有什么区别吗?
  • 打赏
  • 举报
回复
<script type="text/javascript">

var Student = function(name) {
this.name = name;
}

Student.prototype = {

getName : function() {
return this.name;
},

setName : function(name) {
this.name = name;
},

toString : function() {
return 'name: ' + this.name;
}
}

window.onload = function() {
var student = new Student('tom');
alert(student.getName());
alert(student.toString());
}

</script>
  • 打赏
  • 举报
回复
这样定义的话,一般是放在原型链 prototype 中吧?否则是不能这样用的

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧