zoukankan      html  css  js  c++  java
  • js创建对象之原型模式4、重新原型

    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="UTF-8">
    		<title></title>
    	</head>
    	<body>
    		<script type="text/javascript">
    		//创建对象之原型模式
    		//由于由于在原型查找值的过程是一个搜索的过程,所以我们修改prototype属性。立即能够体现出来
    		function Person(){};
    		var friend = new Person();	//先创建实例
    		
    		Person.prototype.sayHi = function(){
    			console.log('Hi');
    		}	//后给原型添加属性
    		
    		friend.sayHi();	//能够正常运行
    		
    		console.log('------------------------------------');
    		//但是如果要是重写原型那么情况就不一样了
    		//当我们new一个function的时候得到实例对象
    		//同事创建了[[prototype]]指针指向了原型对象
    		//重写prototype之后,即prototype = {}之后,prototype指向了新的对象
    		//而实例仍然指向了原来的prototype对象
    		function Person(){};
    		var friend = new Person();
    		Person.prototype = {
    			constructor: Person,
    			name: "宝清老窖",
    			age: 29,
    			job: "Software",
    			sayName: function(){
    				console.log(this.name);
    			}
    		}
    		friend.sayName();	//error  friend.sayName is not a function
    		
    		//所以原型的重写要注意
    		</script>
    	</body>
    </html>
    

      提取js

    //创建对象之原型模式
    		//由于由于在原型查找值的过程是一个搜索的过程,所以我们修改prototype属性。立即能够体现出来
    		function Person(){};
    		var friend = new Person();	//先创建实例
    		
    		Person.prototype.sayHi = function(){
    			console.log('Hi');
    		}	//后给原型添加属性
    		
    		friend.sayHi();	//能够正常运行
    		
    		console.log('------------------------------------');
    		//但是如果要是重写原型那么情况就不一样了
    		//当我们new一个function的时候得到实例对象
    		//同事创建了[[prototype]]指针指向了原型对象
    		//重写prototype之后,即prototype = {}之后,prototype指向了新的对象
    		//而实例仍然指向了原来的prototype对象
    		function Person(){};
    		var friend = new Person();
    		Person.prototype = {
    			constructor: Person,
    			name: "宝清老窖",
    			age: 29,
    			job: "Software",
    			sayName: function(){
    				console.log(this.name);
    			}
    		}
    		friend.sayName();	//error  friend.sayName is not a function
    		
    		//所以原型的重写要注意
    

      

  • 相关阅读:
    &【12】Python 函数
    &【11】Python 流程控制
    &【09】Python 数据类型之dictionary
    &【07】Python 数据类型之元组
    &【08】Python 数据类型之set
    &【06】Python 数据类型之list
    &【05】Python 彻底搞懂分片操作
    &【04】Python 数据结构之序列
    SpringBoot-HelloWorld(三)
    SpringBoot-了解微服务(二)
  • 原文地址:https://www.cnblogs.com/xudy/p/5427111.html
Copyright © 2011-2022 走看看