Showing posts with label extends. Show all posts
Showing posts with label extends. Show all posts

Saturday, December 20, 2008

用jQuery.extend遇到的问题, 与大家共勉

官方接口: jQuery.extend( [deep], target, object1, [objectN] )

如果target未指定, 则jQuery名字空间接受extend后的属性, 但是, 如果object中包含dom属性, deep又设置为true的话, 则会出现recursively error, 因为dom树存在循环引用!
  • 看代码就很容易明白了,
  • extend函数的核心:
    if ( deep && copy && typeof copy === "object" && !copy.nodeType )
    target[ name ] = jQuery.extend( deep, src || ( copy.length != null ? [ ] : { } ), copy );
  • 可以看到这里copy.nodeType处理了dom node, 就是为了避免这种递归, 但是当我们自己有个对象, 此对象是互相引用的结构时, 这个情况就再所难免了, 所以一定要注意
  • 另外: $.ajax({param: ...}), 中的param, ajax函数内部就是一个jQuery.extend, 所以这里也要注意一下


Saturday, October 11, 2008

js简单继承的实现 - 网上做法修正篇

网上有些继承prototype实现上有bug例如:

function base() {
this.member = ["dnnsun_Member",2,3,4];
}
var child=function(){
};

child.prototype=new base;
var c1 = new child();
var c2 = new child();
c1.member[1]=333;
alert(c2.member[1]);

结果是: 333

base中如果有集合, 对象属性, 这种简单继承导致的后果是所有的child的实例都共享了base的同一个member属性. 所以要尽量避免此种情况, 尽量在父类中只是定义方法, 变量改为传入的方式. 估计这也是为什么jquery, ext等框架不强制继承的子类必须subclass_instance instanceof superclass==true的原因.

Saturday, October 04, 2008

js简单继承的实现, 改进篇

前文表述: js简单继承的实现

前文问题:
alert(child instanceof base); 打印false, 此处并没有实现真正的继承

改进:
function base() {
this.member = "dnnsun_Member";
this.test=function(){
window.alert('in base');
}
}

base.prototype.test= function() {
window.alert("base member "+this.member);
}

function extend(child, b) {
b.call(child);
child.prototype=new b;
}
var childclass=function(){
this.test=function(){
window.alert("in child");
}
};


extend(childclass, base);

child = new childclass;

window.alert(child.member);
window.alert(child.test);
child.test();
window.alert(child instanceof base);

Friday, June 20, 2008

js简单继承的实现

function base() {
this.member = "dnnsun_Member";
this.method = function() {
window.alert(this.member);
}
}
function extend(child, b) {
b.call(child);
}
var child={
test:function(){
window.alert("in child");
window.alert(child.member);
}
};
extend(child, base);
window.alert(child.member);
window.alert(child.method);
child.test()