Js面向对象的个人理解

来源:互联网 发布:js回车事件 编辑:程序博客网 时间:2024/06/04 18:16

JS对象理解

1、 js对象就是键值对的集合

2、 js里函数就是对象

3、 普通函数function(对象)

 function function_name(argument) {    // body...}

4. 构造函数就是普通函数多了this(构造函数生成的对象)

function function_name(argument) {    this.name=argument    this.getName=function(){        return this.name    }}

5、js里每一个构造函数(对象或普通函数)都有一个原型(prototype)属性其是一个对象

6、原型链:因为原型也是对象所以也有其原型这就组成了一条链,js中访问属性时在对象本身先查找->原型链中查找->未找到则为undefined

7、通过prototype设置对象(与构造函数相比占用内存小)

function function_name(argument) {    // body...}function_name.prototype.name='这是对象名称';function_name.prototype.getName=function(){    return this.name;}

8、继承有构造函数绑定

* 使用call或apply方法,将父对象的构造函数绑定在子对象上,即在子对象构造函数中加一行:

function Children(name,color){        Parent.apply(this, arguments);    this.name = name;    this.color = color;  }

* 使用prototype原型属性

Children.prototype = new Parent();Children.prototype.constructor = Children;

prototype对象都有一个constructor属性,指向它的构造函数,没有第二行则Children对象的原型的constructor属性指向的构造函数为Parent当实例化一个children时实例化的对象的构造函数也为Parent这就造成了紊乱,所以需要让其指回原来的构造函数

* 直接继承Parent的prototype

function Parent(){ }    Parent.prototype.name = "这是父对象名称";    Children.prototype=Parent.prototype;    Children.prototype.constructor=Children;

优点(省内存)缺点(Parent.prototype.constructor也指向Children了)

利用中间对象(一个空对象)

var F = function(){};    Parent.prototype.name = "这是父对象名称";    F.prototype=Parent.prototype;    Children.prototype=F.prototype;    Children.prototype.constructor=Children;

上面的代码同样会使parent.prototype.construct指向children
因为js有值传递(变量)和引用传递(指针)
Js对象 共享对象传递意思就是对象本身属于值传递,属性、方法属于引用传递

var obj={x:1}function foo(o) {    o.x = 3;    console.log(obj.x); // 3, 被修改了!    o=true;}foo(obj);console.log(obj.x);//3,obj未被修改为true

所以应该为

var F = function(){};    Parent.prototype.name = "这是父对象名称";    F.prototype=Parent.prototype;    Children.prototype=new F();    Children.prototype.constructor=Children;//这里只是改变新new的F()实例的constructor而原型的constructor不变即new的实例.constructor==Children为真
原创粉丝点击