JavaScript基础(12.面向对象及原型简介)

来源:互联网 发布:简易流程图制作软件 编辑:程序博客网 时间:2024/05/22 03:27

面向对象的基本知识就不讲了:

function Foo(n){    this.name = n;}var obj = new Foo("yiq")/*这就表示创建了一个对象,注意必须要用new*/
这里就创建了一个对象


<script>function Foo (name,age) {    this.Name = name;    this.Age = age;    this.Func = function(arg){        return this.Name + arg;    }}var obj = new Foo('yiq', 18);var ret = obj.Func("uin");console.log(ret);</script>

对于上述代码需要注意:

  • Foo充当的构造函数
  • this代指对象
  • 创建对象时需要使用 new

上述代码中每个对象中均保存了一个相同的Func函数,从而浪费内存。使用原型和可以解决该问题:


<script>function Foo (name,age) {    this.Name = name;    this.Age = age;}Foo.prototype = {    GetInfo: function(){        return this.Name + this.Age    },    Func : function(arg){        return this.Name + arg;    }}</script>

看上去很复杂,其实只需要先记下来,以后用到时候自然就理解了。


阅读全文
0 0