<script type="text/javascript">
//1.可以通过new对象的方法,称之为“构造函数”,采用pascal命名法
function Person(name,age,email) {
this.name = name;
this.age = age;
this.email = email;
this.sayHello = function () {
alert('hi,我叫' + this.name + '我今年' + this.age + '岁了');
};
}
var zs = new Person('张三', 18, '[email protected]');
var ls = new Person('李四', 22, '[email protected]');
zs.sayHello();
ls.sayHello();
//2.给“构造函数”创建一个私有的“字段”,并用两个函数模拟属性
function Person2(name, age, email) {
this.name = name;
this.age = age;
this.email = email;
this.sayHi = function () {
alert('我是:' + this.name + '今年:' + this.age + '岁了,邮箱是:' + this.email);
};
var _gender;
this.getGender = function () {
return _gender
};
this.setGender = function (gender) {
if (gender == '男' || gender=='女') {
_gender = gender;
}
else {
alert('性别别乱填,小心变了哦');
}
}
}
var mtt = new Person2('马婷婷', 22, '[email protected]');
var ltt = new Person2('老太太', 88, '[email protected]');
mtt.sayHi();
ltt.sayHi();
mtt.setGender('x');
//3.校验实例instanceof 相当于C#中的is(如果是属于类返回true,不属于返回false)
if (mtt instanceof Person2) {
document.write('没错,mtt就是Person2');
};
//4.通过对象字面量创建对象(只用一次的对象,不创建"构造函数")
var wll = {
user_name: '王拉拉',
user_age: 18,
user_gender: '女神',
sayHi: function () {
alert('我叫' + this.user_name + '今年' + this.user_age);
}
};
wll.sayHi();
JS面向对象练习
猜你喜欢
转载自blog.csdn.net/BowenXu11/article/details/105225665
今日推荐
周排行