function Person(name,age)
{
this.name = name;
this.age = age;
this.sayName = fun;
};
function fun()
{
alert(this.name);
}
var per1 = new Person('zhzhz',50);
var per2 = new Person('ccccccc',30);
console.log(per1 instanceof Person);//instanceof判断是否为某个类
console.log(per1.sayName == per2.sayName);
以上方法因为定义了全局的函数,可能造成函数名污染,可用以下方法替换
/*
* 原型prototype
* 创建的每一个函数解析器都会添加prototype属性
*/
function Person(name,age)
{
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
alert("hello");
}
var person = new Person();
person.sayHello();
console.log(Person.prototype);
//in : 判断person对象中是否含有名为name的属性,包括原型中的属性
console.log("sayHello" in person);//true
//hasOwnProperty:判断person对象中是否含有名为name的属性,不包括原型中的属性
console.log(person.hasOwnProperty("name"));//true
console.log(person.hasOwnProperty("sayHello"));//false
console.log(person.__proto__.hasOwnProperty("sayHello"));//true
2191

被折叠的 条评论
为什么被折叠?



