【前端开发】面向对象编程案例创建对象


<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title>
</head> <body> <button>one</button> <button>two</button> <button>three</button> <script src="https://topmdrt-static.oss-cn-shenzhen.aliyuncs.com/static/js/common/zepto.min.2.js"></script> <script type="text/javascript"> //面向对象编程创建对象 function student(name, age) { this.name = name; this.hello = function() { if(age) { //存在age参数执行 console.log('hello' + name + '我是' + age) } else { //不存在age参数执行 console.log('hello' + name) } } } // student('xiaoming') //这样写是无法执行hello()的 var child = new student('xiaohong'); //重新构造函数,调用传参即可 var child2 = new student('第二个函数'); var child3 = new student('第三个了哦', '26岁'); child.hello(); //执行 child2.hello(); child3.hello(); //点击事件传参,点击触发构造函数及执行 $('button').on('click', function() { var $this = $(this).text(); var child4 = new student('第四个了哦', $this + '岁'); child4.hello(); }) //创建基于原型的JavaScript的对象 student.prototype.say = function() { alert('添加成功') } var say1 = new student('这是用来测试的'); say1.say(); </script> </body> </html>

  

猜你喜欢

转载自www.cnblogs.com/xiaohuizhang/p/8979351.html