面向对象的程序设计(二)理解各种方法和属性typeof、instanceof、constructor、prototype、__proto__、isPrototypeOf、hasOwnProperty

//理解各种方法和属性typeof、instanceof、constructor、prototype、__proto__、isPrototypeOf、hasOwnProperty、
//1、typeof方法 获取变量的类型,返回:number, string, undefined, object, boolean, function
console.log("typeof方法");
var st = "abcd";

console.log(typeof st);//string        也可以用typeof(st);

//2、instanceof方法 判断变量是否是某个对象的实例,返回:true或false
console.log("instanceof方法");
var arr = [1, 2];
function Person() {

}
var person1 = new Person();

console.log(arr instanceof Array);//true
console.log(st instanceof Array);//false
console.log(person1 instanceof Person);//true

//3、constructor属性 指向创建实例构造函数
//对象原型中也有一个constructor属性,也是指向构造函数
console.log("constructor属性");
function Person2() {

}
var person2 = new Person2();

console.log(person2.constructor);//返回的是Person2        console.log(person2.constructor == Person2)
console.log(Person2.prototype.constructor);//返回的是Person2        console.log(person2.constructor == Person2)

//4、prototype属性    指向函数的原型,存在于构造函数与构造函数原型之间
//5、__proto__        指向实例的构造函数的原型对象,存在于实例与构造函数的原型对象之间(这个属性是不可见的,不过在FF, chrome, safari等浏览器中可以通过脚本访问)
console.log("__proto__属性");
function Person3() {

}
var person3 = new Person3();
var person4 = new Person3();

console.log(person3.__proto__ == Person3.prototype);//true
console.log(person4.__proto__ == Person3.prototype);//true

//6、isPrototypeOf方法:用来判断要检查其原型链的对象是否存在于指定对象实例中,是则返回true,否则返回false
//7、hasOwnProperty方法:用来判断一个对象是否有你给出名称的属性或对象。不过需要注意的是,此方法无法检查该对象的原型链中是否具有该属性,该属性必须是对象本身的一个成员。
console.log("isPrototypeOf方法、hasOwnProperty方法")
function siteAdmin(nickName,siteName){
            this.nickName=nickName;
            this.siteName=siteName;
        }
        siteAdmin.prototype.showAdmin = function() {
            alert(this.nickName+"是"+this.siteName+"的站长!")
        };
        siteAdmin.prototype.showSite = function(siteUrl) {
            this.siteUrl=siteUrl;
            return this.siteName+"的地址是"+this.siteUrl;
        };
        var matou=new siteAdmin("愚人码头","WEB前端开发");
        var matou2=new siteAdmin("愚人码头","WEB前端开发");
        matou.age="30";
//      matou.showAdmin();
//      alert(matou.showSite("http://www.css88.com/"));
        console.log(matou.hasOwnProperty("nickName"));//true
        console.log(matou.hasOwnProperty("age"));//true
        console.log(matou.hasOwnProperty("showAdmin"));//false
        console.log(matou.hasOwnProperty("siteUrl"));//false
        console.log(siteAdmin.prototype.hasOwnProperty("showAdmin"));//true
        console.log(siteAdmin.prototype.hasOwnProperty("siteUrl"));//false
        console.log(siteAdmin.prototype.isPrototypeOf(matou))//true
        console.log(siteAdmin.prototype.isPrototypeOf(matou2))//true

 

posted @ 2013-06-19 18:51  金帛  阅读(289)  评论(0编辑  收藏  举报