`

define subclass - js

    博客分类:
  • js
 
阅读更多

 

define subclass - js

 

------

define subclass

 

definition of subclass:

assume there are function A and B, if A.prototype.prototype = B.prototype, then A is subclass of B,

to complete the subclass, there are more things to do than extends prototype, see following steps,

 

steps to create subclass: 

* B.prototype extends from A.prototype

* B.prototype.constructor = B

* in B's constructor body

* use apply()/call() to invoke B's constructor with arguments,

* define new things for B,

* override A's method/property, if necessary,

* define things on new constructor

 

------

how create a prototype extends from another prototype

 

how to create sub prototype:

create a new function whose prototype is the super prototype, then the new function could be used as the sub prototype,

how to do:

* in ECMAScript5:

use Object.create(p),

* in ECMAScript3:

create an function, point its prototype to ther super prototype,

 

util function to create a sub prototype:

	/**
	  * create a sub prototype which extends from specified super prototype
	  * 
	  * @param: p 
			super prototype
	  * @return
			sub prototype
	  */
	function inherit(p) {
	    if (p == null) throw TypeError(); // p must be a non-null object
	    if (Object.create)                // If Object.create() is defined...
		return Object.create(p);      //    then just use it.
	    var t = typeof p;                 // Otherwise do some more type checking
	    if (t !== "object" && t !== "function") throw TypeError();
	    function f() {};                  // Define a dummy constructor function.
	    f.prototype = p;                  // Set its prototype property to p.
	    return new f();                   // Use f() to create an "heir" of p.
	}

 

 

------

abstract class / interface

 

abstract class & interface:

are class that include abstract method, in js abstract method could be a method that throw an exception,

 

implementation:

in the subclass, override the abstract method, thus get a class without abstract method,

 

------

e.g.

 

include:

 

* inherit_util.js

include some util methods for inherit,

* subclass_example_1.js

a example use inherit()/extend() directly,

* subclass_example_2.js

a example use defineSubclass(),

* subclass_example_3.js

a example use Function.prototype.extend(),

 

 

 

inherit_util.js:

/**
 * util function copy enumerable property of p to object o
 * 
 * @param o
 * @param p
 * @returns
 */
function extend(o, p) {
	for (prop in p) { // For all props in p.
		o[prop] = p[prop]; // Add the property to o.
	}
	return o;
}

/**
 * create a prototype which inherit from specified prototype
 * 
 * @param p
 *            super prototype
 * @returns sub prototype
 */
function inherit(p) {
	if (p == null)
		throw TypeError(); // p must be a non-null object
	if (Object.create) // If Object.create() is defined...
		return Object.create(p); // then just use it.
	var t = typeof p; // Otherwise do some more type checking
	if (t !== "object" && t !== "function")
		throw TypeError();
	// Define a dummy constructor function.
	function f() {
	}

	f.prototype = p; // Set its prototype property to p.
	return new f(); // Use f() to create an "heir" of p.
}

/**
 * util function to define subclass, extends from specified superclass, and add
 * new methods/properties to prototype/constructor, this function depends on
 * extend() & inherit(),
 * 
 * @param superclass
 *            Constructor of the superclass
 * @param constructor
 *            The constructor for the new subclass
 * @param methods
 *            Instance methods to copied to prototype, the param should be an
 *            object contain methods/properties
 * @param statics
 *            Class properties to copied to constructor, the param should be a
 *            object contain methods/properties,
 * @return the new constructor
 */
function defineSubclass(superclass, constructor, methods, statics) {
	// inherit from super prototype
	constructor.prototype = inherit(superclass.prototype);
	// set the constructor property of the new prototype
	constructor.prototype.constructor = constructor;
	// copy instance properties/methods to copied to prototype
	if (methods)
		extend(constructor.prototype, methods);
	// copy class properties/methods to constructor
	if (statics)
		extend(constructor, statics);
	// Return the class
	return constructor;
}

/**
 * add the extend method to js Function, so that apply to all function of js,
 * 
 * @param constructor
 * @param methods
 * @param statics
 * @returns the new constructor
 */
Function.prototype.extend = function(constructor, methods, statics) {
	return defineSubclass(this, constructor, methods, statics);
};
/**
 * an abstract method, which throws error
 */
function abstractMethod() {
	throw new Error("method not implemented");
}

 

 

subclass_example_1.js:

// depends on inherit_util.js

// super class
function A() {
	this.pone = "A-pone";
	this.ptwo = "A-ptwo";
}
A.prototype.mone = function() {
	console.log("A-mone");
};
// super class has a abstract method
A.prototype.mtwo = abstractMethod;
A.prototype.mthree = function() {
	console.log("A-mthree");
};

// sub class
function B() {
	// invoke super constructor on sub object, so that to extends things defined
	// in super constructor,
	A.apply(this);
	// override super property from super constructor,
	this.pone = "B-pone";
}
// extends from super prototype
B.prototype = inherit(A.prototype);
// set the constructor property of sub prototype, after extends prototype,
B.prototype.constructor = B;
// implemet(override) abstract method of super class
B.prototype.mtwo = function() {
	console.log("B-mtwo");
};
// override method of super class
B.prototype.mthree = function() {
	console.log("B-mthree");
};

function test() {
	var b = new B();
	b.mone();
	b.mtwo();
	b.mthree();
	console.log(b.pone);
	console.log(b.ptwo);
}
test();

 

 

subclass_example_2.js:

// depends on inherit_util.js

// super class
function A() {
	this.pone = "A-pone";
	this.ptwo = "A-ptwo";
}
A.prototype.mone = function() {
	console.log("A-mone");
};
// super class has a abstract method
A.prototype.mtwo = abstractMethod;
A.prototype.mthree = function() {
	console.log("A-mthree");
};

// sub class
function B() {
	// invoke super constructor on sub object, so that to extends things defined
	// in super constructor,
	A.apply(this);
	// override super property from super constructor,
	this.pone = "B-pone";
}

// extends from super prototype
defineSubclass(A, B, {
	mtwo : function() {
		console.log("B-mtwo");
	},
	mfour : function() {
		console.log("B-mfour");
	}
}, {
	sfone : "staticFieldOne"
});

function test() {
	var b = new B();
	b.mone();
	b.mtwo();
	b.mthree();
	b.mfour();
	console.log(b.pone);
	console.log(b.ptwo);
	console.log(b.constructor.sfone);
}
test();

 

 

subclass_example_3.js:

 

// depends on inherit_util.js

// super class
function A() {
	this.pone = "A-pone";
	this.ptwo = "A-ptwo";
}
A.prototype.mone = function() {
	console.log("A-mone");
};
// super class has a abstract method
A.prototype.mtwo = abstractMethod;
A.prototype.mthree = function() {
	console.log("A-mthree");
};

// sub class
function B() {
	// invoke super constructor on sub object, so that to extends things defined
	// in super constructor,
	A.apply(this);
	// override super property from super constructor,
	this.pone = "B-pone";
}

// extends from super class
A.extend(B, {
	mtwo : function() {
		console.log("B-mtwo");
	},
	mfour : function() {
		console.log("B-mfour");
	}
}, {
	sfone : "staticFieldOne"
});

function test() {
	var b = new B();
	b.mone();
	b.mtwo();
	b.mthree();
	b.mfour();
	console.log(b.pone);
	console.log(b.ptwo);
	console.log(b.constructor.sfone);
}
test();
 

 

------


分享到:
评论

相关推荐

    FLUENT UDFs 金属材料属性udf,表面张力、DEFINE-PROTERTY、DEFINE-SPECIFIC-HEAT

    标题中的"FLUENT UDFs 金属材料属性udf,表面张力、DEFINE-PROPERTY、DEFINE-SPECIFIC-HEAT"涉及了UDFs在模拟金属材料特性的应用,特别是关于不锈钢的热力学性质。 首先,我们来看`DEFINE-PROPERTY`和`DEFINE-...

    UDF 动网格,DEFINE-CG-MOTION,DEFINE-GRID-MOTION

    `DEFINE_CG_MOTION`和`DEFINE_GRID_MOTION`是UDF编程中用于定义网格运动的两个关键函数。它们是ANSYS Fluent内建的宏,用于在UDF中指定网格如何随时间变化。 1. `DEFINE_CG_MOTION`:这个宏主要用于定义中心点...

    前端开源库-define-frozen-property

    "define-frozen-property"是一个这样的开源库,它专注于定义并冻结JavaScript对象的属性。冻结属性是一个重要的概念,它涉及到JavaScript的原型继承、对象属性特性以及数据安全等方面。在这篇文章中,我们将深入探讨...

    eslint-define-config:为.eslintrc.js文件提供defineConfig函数

    eslint-define-config 为.eslintrc.js文件提供defineConfig函数。 安装 # add eslint and eslint-define-config to project’s dev dependencies npm install --dev eslint eslint-define-config # or yarn add --...

    017-define-func-2-args.rar_The Test

    在本讨论中,我们将深入探讨"017-define-func-2-args.rar_The Test"这个主题,它涉及到图形处理单元(GPU)中的关键特性——模板测试和快速Z清除。 首先,我们要理解什么是模板测试。在计算机图形学中,模板测试是...

    define用法-C语言.pdf

    在C语言中,预处理器指令#define用于创建宏,这是一种在编译之前的代码替换机制。宏可以定义常量、函数或更复杂的代码结构。本文将详细解释多种#define用法,并展示如何使用这些预处理宏。 1. 定义常量 #define用于...

    define-rollup-config:具有类型注释的汇总配置创建方法

    npm install define-rollup-config -D # yarn yarn add define-rollup-config -D 用法 // rollup.config.js import defineRollupConfig from "define-rollup-config" ; export default defineRollupConfig ( { // ...

    define-lazy-prop:在对象上定义惰性计算的属性

    安装$ npm install define-lazy-prop用法import defineLazyProperty from 'define-lazy-prop' ;const unicorn = {// …} ;defineLazyProperty ( unicorn , 'rainbow' , ( ) => expensiveComputation ( ) ) ;app . on...

    definelazyprop在对象上定义延迟计算的属性

    总结来说,`define-lazy-prop`是一个实用的JavaScript工具,可以帮助开发者在对象上定义延迟计算的属性,优化性能,减少不必要的计算。通过正确使用这个库,你可以更好地控制代码的执行时间和资源消耗,尤其在处理...

    前端开源库-define-configurable

    "define-configurable"是一个专门为前端开发设计的开源库,它专注于定义和管理对象的可配置属性。这个库利用了JavaScript语言中的核心特性——`Object.defineProperty()`方法,帮助开发者更加灵活地控制对象的属性...

    gulp-define-vm-module

    gulp-define-vm-modulegulp-define-vm-module 此插件可以将browserify合并规则的源代码合成为CMD风格的模块化文件.define('moduleName', function(require, exports, module){var mod = (browserify script);...

    define用法以及.doc

    `#define`是C/C++预处理器中的一个指令,用于创建宏定义,它可以在编译期间替换特定的文本。下面是对`#define`用法及其与`typedef`区别的详细解释: 1. **简单的宏定义**: `#define`常用于定义常量,如`#define ...

    NX二次开发UF-DRAW-define-view-boundary1 函数介绍

    NX二次开发UF_DRAW_define_view_boundary1 函数介绍,Ufun提供了一系列丰富的 API 函数,可以帮助用户实现自动化、定制化和扩展 NX 软件的功能。无论您是从事机械设计、制造、模具设计、逆向工程、CAE 分析等领域的...

    NX二次开发UF-DRAW-define-view-manual-rect 函数介绍

    NX二次开发UF_DRAW_define_view_manual_rect 函数介绍,Ufun提供了一系列丰富的 API 函数,可以帮助用户实现自动化、定制化和扩展 NX 软件的功能。无论您是从事机械设计、制造、模具设计、逆向工程、CAE 分析等领域...

    NX二次开发UF-DRAW-define-bound-by-objects 函数介绍

    NX二次开发UF_DRAW_define_bound_by_objects 函数介绍,Ufun提供了一系列丰富的 API 函数,可以帮助用户实现自动化、定制化和扩展 NX 软件的功能。无论您是从事机械设计、制造、模具设计、逆向工程、CAE 分析等领域...

    NX二次开发UF-DRAW-define-view-auto-rect 函数介绍

    NX二次开发UF_DRAW_define_view_auto_rect 函数介绍,Ufun提供了一系列丰富的 API 函数,可以帮助用户实现自动化、定制化和扩展 NX 软件的功能。无论您是从事机械设计、制造、模具设计、逆向工程、CAE 分析等领域的...

    How-to-Define-and-Use-Formatted-Search_SAPB1FormatSearch_

    How to Define and Use Formatted Search in SAP business one

    user-define-js-action-test

    世界您好JavaScript操作此操作将打印“ Hello World”或“ Hello” +要向日志打招呼的人的姓名。输入项who-to-greet 必需要问候...用法示例使用:hello-world-javascript-action@v1.1和:问候对象:“ Octocat蒙娜猫”

    axy-define-asm:装配 axy.define 项目

    axy-define-asm --source=js --outDir=outJS 没有参数,只有选项: --addExt=ext Add an extension to assembly -a, --all Add all files --allText Process all files as text --appendVars=vars Append vars ...

    NX二次开发UF-DRAW-define-view-boundary 函数介绍

    NX二次开发UF_DRAW_define_view_boundary 函数介绍,Ufun提供了一系列丰富的 API 函数,可以帮助用户实现自动化、定制化和扩展 NX 软件的功能。无论您是从事机械设计、制造、模具设计、逆向工程、CAE 分析等领域的...

Global site tag (gtag.js) - Google Analytics