面向对象object和constructor

构造函数(Constructor),是一种特殊的方法,主要用来在创建对象时初始化对象,即为对象成员变量赋初始值。总与new运算符一起使用在创建对象的语句中,特别的一个类可以有多个构造函数,可根据其参数个数的不同或参数类型的不同来区分它们,即构造函数的重载

语法:object.constructor (js)

返回值:js对象的constructor属性返回创建该对象的函数的引用。
实例:
以下代码中的[native code],表示这是JavaScript的底层内部代码实现,无法显示代码细节。
// 字符串:String()
var str = "张三";
document.writeln(str.constructor); // function String() { [native code] }
document.writeln(str.constructor === String); // true
// 数组:Array()
var arr = [1, 2, 3];
document.writeln(arr.constructor); // function Array() { [native code] }
document.writeln(arr.constructor === Array); // true
// 数字:Number()
var num = 5;
document.writeln(num.constructor); // function Number() { [native code] }
document.writeln(num.constructor === Number); // true
// 自定义对象:Person()
function Person(){
this.name = "CodePlayer";
}
var p = new Person();
document.writeln(p.constructor); // function Person(){ this.name = "CodePlayer"; }
document.writeln(p.constructor === Person); // true
// JSON对象:Object()
var o = { "name" : "张三"};
document.writeln(o.constructor); // function Object() { [native code] }
document.writeln(o.constructor === Object); // true
// 自定义函数:Function()
function foo(){
alert("CodePlayer");
}
document.writeln(foo.constructor); // function Function() { [native code] }
document.writeln(foo.constructor === Function); // true
// 函数的原型:bar()
function bar(){
alert("CodePlayer");
}
document.writeln(bar.prototype.constructor); // function bar(){ alert("CodePlayer"); }
document.writeln(bar.prototype.constructor === bar); // true

Constructor的常用方法:

1.String getName();获得方法名。

2.int getModifiers();获得修饰符。

3.Class[] getParamenterTypes();获得构造方法的参数类型。

4.newInstance(Object...args);使用当前的构造方法来创建一个对象。

猜你喜欢

转载自www.cnblogs.com/tianshao/p/9944251.html