//利用构造函数自定义对象
var stu1 = new Student("smyh");
console.log(stu1);
stu1.sayHi();
var stu2 = new Student("vae");
console.log(stu2);
stu2.sayHi();
// 创建一个构造函数
function Student(name) {
this.name = name; //this指的是当前对象实例【重要】
this.sayHi = function () {
console.log(this.name + "厉害了");
}
}
// 创建一个构造函数,专门用来创建Person对象
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.sayName = function() {
alert(this.name);
};
}
var per = new Person("孙悟空", 18, "男");
var per2 = new Person("玉兔精", 16, "女");
var per3 = new Person("奔波霸", 38, "男");
// 创建一个构造函数,专门用来创建 Dog 对象
function Dog() {}
var dog = new Dog();
// 创建一个函数
function createStudent(name) {
var student = new Object();
student.name = name; //第一个name指的是student对象定义的变量。第二个name指的是createStudent函数的参数。二者不一样
}
// 创建一个函数
function Student(name) {
this.name = name; //this指的是构造函数中的对象实例
}
对象 instanceof 构造函数
function Person() {}
function Dog() {}
var person1 = new Person();
var dog1 = new Dog();
console.log(person1 instanceof Person); // 打印结果: true
console.log(dog1 instanceof Person); // 打印结果:false
console.log(dog1 instanceof Object); // 所有的对象都是Object的后代。因此,打印结果为:true