<!DOCTYPE html>
<html>
<head>
<title>create obj</title>
</head>
<body>
<script type="text/javascript">
// ********************************
// 工程模式
function createObj(name) {
// body...
var o = new Object();
o.name = name;
o.hello = function () {
alert('hello')
}
return o;
}
var newobj = createObj('ytt');
newobj.hello();
// ********************************
// 构造函数
function Person(name) {
this.name = name;
this.hello = function () {
alert('hello')
}
}
var person1 = new Person('ytt');
var person2 = new Person('tjj');
console.log(person1.hello === person2.hello)
console.log(person1.hello, person2.hello)
person1.hello();
// 区别:没有return语句;直接将this对象赋给了新对象;需要用new操作符;没有显示的创建对象
// 过程:1. 创建新对象 2.this指向新对象 3. 执行构造函数 4. 返回新的对象
// 缺点:每构建一个实例,就新建一个方法,每个方法属于不同的Function实例,不同实例上的同名函数不同
/*
改进: 将hello定义为全局的变量,构造函数指向这个函数的指针,每个实例公用一个指向这个函数的指针。
缺点: 如果方法比较多,全局函数就会比较多了,不符合模块化思想
function Person(name) {
this.name = name;
this.hello = hello;
}
function hello = function () {
alert('hello')
}*/
// *******************************************
// 原型方法
function Person() {
}
Person.prototype.name = 'ytt'
Person.prototype.hello = function () {
alert('hello')
};
var person1 = new Person()
person1.hello();
console.log(Object.getPrototypeOf(person1));
console.log(Object.getPrototypeOf(person1) == Person.prototype);
console.log(Person.prototype.isPrototypeOf(person1))
console.log(person1.hasOwnProperty('name'))
/*function Person() {
}
Person.prototype = {
// constructor: Person, //但是这种方式会导致constructor变成可枚举属性
name: 'ytt',
hello: function () {
alert('hello')
}
}
Object.defineProperty(Person.prototype, 'constructor', {
enumberable: false,
value: Person
}); //这样变成不可枚举属性
var person1 = new Person();
console.log(person1 instanceof Person);
console.log(Person.prototype.constructor);
console.log(person1.constructor);*/
// **********************************************
// 原型的动态性
/*function Person() {
}
var person1 = new Person();
Person.prototype = {
name: name,
hello: function () {
alert('hello')
}
}
console.log(person1.name) // undefined,prototype指向的是原来的原型对象,不是新的*/
// ***************************************************
// 组合使用构造函数和原型函数
function Person (name) {
this.name = name;
}
Person.prototype.hello = function () {
alert('hello');
}
var person1 = new Person('ytt');
var person2 = new person2('tjj');
</script>
</body>
</html>