淺談javascript的原型繼承
更新時間:2012年07月25日 22:47:36 作者:
javascript的繼承在很多框架中都有運(yùn)用,尤其是原型式繼承。首先要理解一個概念,什么是原型式繼承?所謂的原型式繼承,就是在函數(shù)內(nèi)部先創(chuàng)建一個臨時性的構(gòu)造函數(shù),然后將傳入的對象做這個構(gòu)造函數(shù)的原型,最后返回這個臨時類型的新實例
請看源碼:
function clone(o) {
var F = function(){};
F.prototype = o;
return new F();
}
首先看ext(4.1的1896行開始)的原型式繼承。
var TemplateClass = function(){};
var ExtObject = Ext.Object = {
chain: function (object) {
TemplateClass.prototype = object;
var result = new TemplateClass();
TemplateClass.prototype = null;
return result;
}
}
這里清除了object的prototype。
再看一下jquery是怎么玩的繼承。
var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context, rootjQuery );
};
-----------------------
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
-----------------------
}
}
-------------------
jQuery.fn.init.prototype = jQuery.fn;
jquery玩的就比較高,借助jQuery.fn.init來完成,但是思路一樣。
司徒正美的mass里也有類似的繼承,在lang_fix.js里面第17行:
create: function(o){
if (arguments.length > 1) {
$.log(" Object.create implementation only accepts the first parameter.")
}
function F() {}
F.prototype = o;
return new F();
}
查看了一下es5的官方,找到了他的兼容補(bǔ)?。?
// ES5 15.2.3.5
// http://es5.github.com/#x15.2.3.5
if (!Object.create) {
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = { "__proto__": null };
} else {
if (typeof prototype != "object") {
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
}
var Type = function () {};
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
object.__proto__ = prototype;
}
if (properties !== void 0) {
Object.defineProperties(object, properties);
}
return object;
};
}
上面的代碼考慮的就比較全面,但是需要另外引入Object.defineProperties的補(bǔ)丁才行,源碼相對就比較多了。
// ES5 15.2.3.6
// http://es5.github.com/#x15.2.3.6
// Patch for WebKit and IE8 standard mode
// Designed by hax <hax.github.com>
// related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
// IE8 Reference:
// http://msdn.microsoft.com/en-us/library/dd282900.aspx
// http://msdn.microsoft.com/en-us/library/dd229916.aspx
// WebKit Bugs:
// https://bugs.webkit.org/show_bug.cgi?id=36423
function doesDefinePropertyWork(object) {
try {
Object.defineProperty(object, "sentinel", {});
return "sentinel" in object;
} catch (exception) {
// returns falsy
}
}
// check whether defineProperty works if it's given. Otherwise,
// shim partially.
if (Object.defineProperty) {
var definePropertyWorksOnObject = doesDefinePropertyWork({});
var definePropertyWorksOnDom = typeof document == "undefined" ||
doesDefinePropertyWork(document.createElement("div"));
if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
var definePropertyFallback = Object.defineProperty;
}
}
if (!Object.defineProperty || definePropertyFallback) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if ((typeof object != "object" && typeof object != "function") || object === null) {
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
}
if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) {
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
}
// make a valiant attempt to use the real defineProperty
// for I8's DOM elements.
if (definePropertyFallback) {
try {
return definePropertyFallback.call(Object, object, property, descriptor);
} catch (exception) {
// try the shim if the real one doesn't work
}
}
// If it's a data property.
if (owns(descriptor, "value")) {
// fail silently if "writable", "enumerable", or "configurable"
// are requested but not supported
/*
// alternate approach:
if ( // can't implement these features; allow false but not true
!(owns(descriptor, "writable") ? descriptor.writable : true) ||
!(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(owns(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
*/
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don't hit an inherited
// accessor.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.__proto__ = prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors) {
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
}
// If we got that far then getters and setters can be defined !!
if (owns(descriptor, "get")) {
defineGetter(object, property, descriptor.get);
}
if (owns(descriptor, "set")) {
defineSetter(object, property, descriptor.set);
}
}
return object;
};
}
// ES5 15.2.3.7
// http://es5.github.com/#x15.2.3.7
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property) && property != "__proto__") {
Object.defineProperty(object, property, properties[property]);
}
}
return object;
};
}
EcmaScript6的類繼承。
class module extends Base {
constructor() {
}
}
越玩越像java了,不過es6很多瀏覽器還不支持。
最后推薦的寫法:
if (!Object.create) {
Object.create = function create(o) {
var F = function(){};
F.prototype = o;
var result = new F();
F.prototype = null;
return result;
}
}
復(fù)制代碼 代碼如下:
function clone(o) {
var F = function(){};
F.prototype = o;
return new F();
}
首先看ext(4.1的1896行開始)的原型式繼承。
復(fù)制代碼 代碼如下:
var TemplateClass = function(){};
var ExtObject = Ext.Object = {
chain: function (object) {
TemplateClass.prototype = object;
var result = new TemplateClass();
TemplateClass.prototype = null;
return result;
}
}
這里清除了object的prototype。
再看一下jquery是怎么玩的繼承。
復(fù)制代碼 代碼如下:
var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context, rootjQuery );
};
-----------------------
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
-----------------------
}
}
-------------------
jQuery.fn.init.prototype = jQuery.fn;
jquery玩的就比較高,借助jQuery.fn.init來完成,但是思路一樣。
司徒正美的mass里也有類似的繼承,在lang_fix.js里面第17行:
復(fù)制代碼 代碼如下:
create: function(o){
if (arguments.length > 1) {
$.log(" Object.create implementation only accepts the first parameter.")
}
function F() {}
F.prototype = o;
return new F();
}
查看了一下es5的官方,找到了他的兼容補(bǔ)?。?
復(fù)制代碼 代碼如下:
// ES5 15.2.3.5
// http://es5.github.com/#x15.2.3.5
if (!Object.create) {
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = { "__proto__": null };
} else {
if (typeof prototype != "object") {
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
}
var Type = function () {};
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
object.__proto__ = prototype;
}
if (properties !== void 0) {
Object.defineProperties(object, properties);
}
return object;
};
}
上面的代碼考慮的就比較全面,但是需要另外引入Object.defineProperties的補(bǔ)丁才行,源碼相對就比較多了。
復(fù)制代碼 代碼如下:
// ES5 15.2.3.6
// http://es5.github.com/#x15.2.3.6
// Patch for WebKit and IE8 standard mode
// Designed by hax <hax.github.com>
// related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
// IE8 Reference:
// http://msdn.microsoft.com/en-us/library/dd282900.aspx
// http://msdn.microsoft.com/en-us/library/dd229916.aspx
// WebKit Bugs:
// https://bugs.webkit.org/show_bug.cgi?id=36423
function doesDefinePropertyWork(object) {
try {
Object.defineProperty(object, "sentinel", {});
return "sentinel" in object;
} catch (exception) {
// returns falsy
}
}
// check whether defineProperty works if it's given. Otherwise,
// shim partially.
if (Object.defineProperty) {
var definePropertyWorksOnObject = doesDefinePropertyWork({});
var definePropertyWorksOnDom = typeof document == "undefined" ||
doesDefinePropertyWork(document.createElement("div"));
if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
var definePropertyFallback = Object.defineProperty;
}
}
if (!Object.defineProperty || definePropertyFallback) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if ((typeof object != "object" && typeof object != "function") || object === null) {
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
}
if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) {
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
}
// make a valiant attempt to use the real defineProperty
// for I8's DOM elements.
if (definePropertyFallback) {
try {
return definePropertyFallback.call(Object, object, property, descriptor);
} catch (exception) {
// try the shim if the real one doesn't work
}
}
// If it's a data property.
if (owns(descriptor, "value")) {
// fail silently if "writable", "enumerable", or "configurable"
// are requested but not supported
/*
// alternate approach:
if ( // can't implement these features; allow false but not true
!(owns(descriptor, "writable") ? descriptor.writable : true) ||
!(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(owns(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
*/
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don't hit an inherited
// accessor.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.__proto__ = prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors) {
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
}
// If we got that far then getters and setters can be defined !!
if (owns(descriptor, "get")) {
defineGetter(object, property, descriptor.get);
}
if (owns(descriptor, "set")) {
defineSetter(object, property, descriptor.set);
}
}
return object;
};
}
// ES5 15.2.3.7
// http://es5.github.com/#x15.2.3.7
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property) && property != "__proto__") {
Object.defineProperty(object, property, properties[property]);
}
}
return object;
};
}
EcmaScript6的類繼承。
復(fù)制代碼 代碼如下:
class module extends Base {
constructor() {
}
}
越玩越像java了,不過es6很多瀏覽器還不支持。
最后推薦的寫法:
復(fù)制代碼 代碼如下:
if (!Object.create) {
Object.create = function create(o) {
var F = function(){};
F.prototype = o;
var result = new F();
F.prototype = null;
return result;
}
}
相關(guān)文章
javascript 網(wǎng)頁跳轉(zhuǎn)的方法
昨天練習(xí)的時候正好要用到跳轉(zhuǎn)代碼,在網(wǎng)上找了一下,覺得下面幾個不錯...整理了一下發(fā)上來...2008-12-12bootstrap使用validate實現(xiàn)簡單校驗功能
這篇文章主要為大家詳細(xì)介紹了bootstrap使用validate實現(xiàn)簡單校驗功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12JavaScript必知必會(三) String .的方法來自何方
這篇文章主要介紹了JavaScript必知必會(三) String .的方法來自何方的相關(guān)資料,非常不錯具有參考借鑒價值,需要的朋友可以參考下2016-06-06基于Flowplayer打造一款免費(fèi)的WEB視頻播放器附源碼
Flowplayer是一款免費(fèi)的WEB視頻播放器。它支持播放flv、swf等流媒體和圖片文件,能夠非常流暢的播放視頻文件,支持自定義配置和擴(kuò)展。下面本篇文章給大家介紹基于Flowplayer打造一款免費(fèi)的WEB視頻播放器,需要的朋友可以參考下2015-09-09JavaScript實現(xiàn)tab欄切換的幾種常用方法
這篇文章主要給大家介紹了關(guān)于JavaScript實現(xiàn)tab欄切換的幾種常用方法,在Web開發(fā)中Tab切換是一個常見的功能,它允許用戶在不同的頁面部分之間進(jìn)行切換,需要的朋友可以參考下2023-12-12