2016년 12월 31일 토요일

location


https://www.blogger.com:8080/blogger.g?blogID=7210508282801009154#editor/target=post;postID=6236407181686720774

----------------------------------
location プロパティ
----------------------------------
window.location.href
window.location.host
window.location.hostname.
window.location.protocol
window.location.port
window.location.pathname
window.location.hash
window.location.search
window.location.username
window.location.password
window.location.origin
---------------------------------
location メソッド
---------------------------------
window.location.reload()
window.location.assign()
window.location.replace()
window.location.toString()
--------------------------------





window.location.href urlのすべて
window.location.host www.blogger.com:8080
window.location.pathname /logger.g
window.location.protocol   https
window.location.hostName www.blogger.com
window.location.port 8080
window.location.hash  #以降すべて
window.location.search ?blogId=72....  ~ #以前まで
window.location.origin  https:www.blogger.com

window.location.reload() 現在のページを再ロード (F5押したときと同様)
window.location.toString()  urlを表示
window.location.assign()  指定urlをロード
window.location.replace() 現在のurlの履歴を削除し、指定urlロード


-----------------------------------------------------------------------------
 http://localhost:8383/HTML5/location.html?userId=1234#gamenId='0303'

locationプロパティ
 


locationメソッド 


        <div id="locationName">
            http://localhost:8383/HTML5/location.html?userId=1234#gamenId='0303'
        </div>
        <div id="result" ></div>
        <div>locationプロパティ
            <button id="location">location</button>
            <button >href</button>
            <button >host</button>
            <button >protocol</button>
            <button >hostname</button>
            <button >pathname</button>
            <button >search</button>
            <button >hash</button>
            <button >username</button>
            <button >password</button>
            <button >origin</button>
        </div>
        <div>locationメソッド
            <button>reload()</button>
           <button>assign()</button>
           <button>replace()</button>
          <button>toString()</button>
        </div>
        <script>
            (function () {
                var buttonTags = $({tagName: 'BUTTON'});

                for (var idx = 0; idx < buttonTags.length; idx++) {
                    var el = buttonTags[idx];
                    el.id = el.innerHTML;
                    buttonTags[idx].addEventListener('click', getProp);
                }

                function getProp() {
                    debugger;
                    var id = event.target.id;
                    if (id === 'location') {
                        window.location = $({id: 'locationName'}).innerHTML;
                        return;
                    }
                   
                    // 指定urlロード
                    if(id === 'assign()'){
                        id = 'assign("http://www.google.co.jp/")';
                    }
                   
                    // 現在の履歴削除して、指定urlロード
                    if(id === 'replace()'){
                        id = 'replace("http://www.yahoo.co.jp/")';
                    }                  
                    var func = "window.location." + id;
                    var result = eval(func);
                    $({id: 'result'}).innerHTML = result;
                }

                function $(obj) {
                    debugger;
                    if (obj['id']) {
                        return document.getElementById(obj['id']);
                    }
                    if (obj['tagName']) {
                        return document.getElementsByTagName(obj['tagName']);
                    }
                }
            })();

        </script>










History



History API

・ブラウザの履歴数取得
・ブラウザの履歴の一つ前に戻る
・ブラウザの履歴の一つ先に進む
・指定の回数分、履歴を前後する
・指定のurlを履歴に追加
・指定のurlを今の履歴に上書き

・window.history.length;
・window.history.back();
・window.history.forward();
・window.history.go($前後の回数);
・window.history.pushState($state, $title, $追加履歴);
・window.history.replaceState($state, $title,$上書き履歴);


--------------------------------------------------------------

        <div>
            historyLength : <span id="historyLength"></span>
            <br>
            <button id="back">back</button>
            <br>
            <a href="#" id="forward">forward</a>
            <br>
            <input type="button" value="go" id="go" />
            <br>
            <input type="text" id="pushState"/>
            <br>
            <button id="replaceState">replaceState</button>
        </div>



        <script type="text/javascript">
            (function () {

                $({id:'historyLength'}).innerHTML = window.history.length;
             
                // タグ名でエレメントを取得
                var btns = $({tagName:'button'});
                var aTag = $({tagName:'a'});
                var inputTag = $({tagName:'input'});

                // button, aタグ, inputタグを配列でforEach関数呼び出す
                forEach([btns, aTag, inputTag]);

                /*
                 * タグ配列を数分、イベントリスナー登録
                 */
                function forEach(tagArray) {
                    // タグ配列分、ループ処理
                    tagArray.forEach(function (item, index, array) {
                     
                        // タグ配列の要素数分、ループ処理
                        for (var idx = 0; idx < item.length; idx++) {
                             var el = item[idx];
                         
                            // INPUTタグ かつ ボタン以外はイベント登録なし
                            if (el.tagName === 'INPUT' && el.type !== 'button') {
                                return;
                            }
                         
                            // イベントリスナー登録処理
                            el.addEventListener('click', function () {
                                           
                                // 上記で判定しているため、不要だが、
tagName判断処理を作成したいため、書いておく
                                if ('BUTTON' === event.target.tagName
                                        || 'A' === event.target.tagName
                                        || 'button' === event.target.type) {
                                    historyExe();
                                }
                            });
                        }
                    });
                }
             
                /*
                 * 履歴関連処理
                 * @returns {undefined}
                 */
                function historyExe() {
                    debugger;
                    var id = event.target.id;
                    var func = "window.history." + id + "()";
                    eval(func);
                };              

                /*
                 * 指定オブジェクトからエレメントを取得
                 */
                function $(obj) {
                    debugger;
                    if(obj['id']){
                         return document.getElementById(obj['id']);                    
                    }
                 
                    if(obj['tagName']){
                        return document.getElementsByTagName(obj['tagName']);                  
                    }
                }

            })();

        </script>
----------------------------------------------------------------



html5 websocket and node.js websocketサーバ

html5のwebsocketとnode.jsのwebsocketサーバーを使い、双方向通信サンプル開発

・websocketTestというexpressプロジェクト生成
express websocketTest

・websocketモジュールインストール
npm install websocket

finalhandler とserve-staticモジュールインストール(localhost:3000/index.htmlのurlからindex.htmlを表示するため:こちらのモジュールがないとクライアントからindex.htmlをリクエストしてもサーバーではindex.htmlを返す処理がないため、index.htmlをレスポンスできない。index.htmlを返す処理を追加することもできるけど、こちらのモジュールをロードして実装することにする)

npm install finalhandler serve-static

-----------------------------------------------
server.js
-----------------------------------------------
var server = require('websocket').server
var http = require('http');

// localhost:3000/index.html --> 画面から直接htmlをリクエストするためのモジュールロード
var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');
var serve = serveStatic("./");

// websocketサーバインスタンス生成し、待機
var socket = new server({

// httpサーバ生成
    httpServer: http.createServer(function(req, res){

// localhost:3000/index.html --> 画面から直接htmlをリクエスト
var done = finalhandler(req, res);
        serve(req, res, done);  
 
  // localhost:3000 --> htmlをレスポンスする処理
  // var fs = require('fs');
// fs.readFile("./index.html", function(errors, data){
// res.writeHead(200, {'Content-Type':'text/html'});
// res.end(data);
//});    
   
    }).listen(3000)  
});

/**
var socket = new server({
    httpServer: http.createServer().listen(3000)  
});
**/

var clients = [ ];

// websocketサーバーにリクエストイベントが発生した場合
socket.on('request', function(request) {

// コネクション取得
    var connection = request.accept(null, request.origin);

var index = clients.push(connection) - 1;

// メッセージを受信した場合の処理
       connection.on('message', function(message) {
   
        console.log(message.utf8Data);
       
        // クライアントからのメッセージを同一コネクションのすべてのクライアントに送信
        for (var i=0; i < clients.length; i++) {
            clients[i].sendUTF(message.utf8Data);
        }
                       
        //setTimeout(function() {
        //    connection.sendUTF('this is a websocket example');
        //}, 1000);
    });

// クライアントがコネクションを切った場合
    connection.on('close', function(connection) {
        console.log('connection closed');
    });
});


-----------------------------------------------
index.html
-----------------------------------------------
<html>
<head>
<style type="text/css">
#msg{
background-color:pink;
}

#content{
background-color:lightgray;
width:500px;
height:200px;
overflow:scroll;
}

#server{
color:red;
}

</style>
</head>
<body>
<div>Enjoy Chat</div>

<div id="content" ></div>

<input type="text"  id="msg" size="50"/><button id="btn">message send...</button></input>

<script type="text/javascript">
 
(function (){
document.getElementById("btn").onclick = send;
var msgEl = document.getElementById("msg");
// 入力欄にフォーカス設定
msgEl.focus();
// キープレスイベントハンドラ登録
msgEl.onkeypress = function(){
if(event.keyCode === 13){
send();
}
}
var chat = document.getElementById('content');

// websocketインスタンス生成
var ws = new WebSocket("ws://localhost:3000/");

// サーバー接続
ws.onopen = function() {
debugger;
console.log('サーバーに接続完了');
}

// 送信処理
function send(){
var msg = document.getElementById('msg').value;
ws.send(msg);
// スクロール調整(直近のメッセージが見えるように)
chat.scrollTop = chat.scrollHeight;
// メッセージ送信完了したら、入力欄をクリア
document.getElementById('msg').value = "";
}

// サーバから受信
ws.onmessage = function(message){
var msgFromSever = message.data;
var attr = {id:'server'};
append(chat, 'P', "from server : " + msgFromSever, attr);
}

// chat内容追加
function append(parent, createTag, text, attr){
// 指定タグ要素を作成、内容をノードに追加
var node = document.createElement(createTag);
var textNode = document.createTextNode(text);
for( key in attr){
node[key] = attr[key];
}
//node['id'] = id;
//node.style = 'color:blue;'
node.appendChild(textNode);
// 親要素に子ノード追加
parent.appendChild(node);
}

})();
   
</script>
</body>
</html>

-----------------------------------------------------
・サーバ開始
node server.js

・url
http://127.0.0.1:3000/index.html




グラフィックス(Canvas)

https://spoqa.github.io/2012/06/13/bitmap-vector.html
http://wacomkorea.tistory.com/624

Canvasは、ブラウザ上に図を描画するための仕様です。
・htmlにCanvas要素を用意
・Canvas要素をjavascriptから参照し、
・描画2d用のContextオブジェクトを取得

1.短形の描画
・現在のpathをリセット
・ブラウザに短形を描画
・塗りつぶし:red
・枠:black
・くり抜く
・pathクローズ

2.テキストの描画
・フォント指定(bold italic サイズ、フォント種類)
・輪郭線のみのテキスト描画
・塗りつぶしのテキスト描画(文字色設定)

3.線の描画
・指定の地点で新規のサブパスを生成
・現在のパスに指定の地点を加え、直前の地点を直線で接続

4.円の描画











1.短形の描画
<html>
中略
<div>
    <canvas id="sample" width="500" height="2000" ></canvas>  
</div>
中略


<script type="text/javascript">
(function () {
    var canvasContext = document.getElementById('sample');
    var context = canvasContext.getContext('2d');
  context.beginPath();
    context.fillStyle = 'red';
    context.strokeStyle = "#000000";
    context.rect(20,50,400,500);
    context.fill();
    context.lineWidth = 5;
    context.stroke();
    context.clearRect(50,80,400,50);
    context.stroke();
    context.closePath();      
})();
</script>

<script type="text/javascript">
(function(){
var canvasEl = document.getElementById('sample');
var ctx = canvasEl.getContext('2d');
ctx.beginPath();
ctx.fillStyle="black";              
ctx.fillRect(10,20,100,150);
ctx.strokeRect(20,30,100,150);
ctx.closePath();              
})();
</html>


2.TEXT
<script type="text/javascript">
    (function (){
        var canvasEl = document.getElementById('sample');
        var ctx = canvasEl.getContext('2d');
        ctx.font = "bold italic 100px sans-serif";
        ctx.strokeStyle = "blue";
        ctx.strokeText('TEXT', 200, 100);
        ctx.font = "bold italic 50px sans-serif";
        ctx.fillStyle="#00FF00";                    
        ctx.fillText('text', 300,200);      
    })();
</script>

3.線の描画
<script type="text/javascript">
    (function(){
        var canvasEl = document.getElementById('sample');
        var ctx = canvasEl.getContext('2d');
        ctx.beginPath();
        ctx.strokeStyle = "green";              
        ctx.moveTo(0, 0);
        ctx.lineTo(90, 90);
        ctx.lineTo(0, 180);
        ctx.stroke();
        ctx.closePath();
        ctx.beginPath();
        ctx.strokeStyle="white";
        ctx.moveTo(200, 200);
        ctx.lineTo(200,300);
        ctx.stroke();
        ctx.closePath();
    })();    
</script>

websocket

http://python.matrix.jp/pages/web/chat_sample.html

WebSocketsってなにができるの?

WebSocketsは双方向ストリーム通信ができる規格
最もメジャーなHTTPは同期型といい、
  1. クライアントからサーバーへつなぎに行く。
  2. クライアントからサーバへデータを送信する。
  3. サーバーからクライアントへデータを返信する。
  4. 接続を切断する。
以上をセットで繰り返し、データの交換を行ないます。 HTTPではこの手順が規定されているので、手順3.に進んでから手順2.をやりたかったら 手順4.まで進めて最初から手順を踏んでいかなければなりません。 手順3.だけを繰り返したい場合も基本のこの手順セットを繰り返す必要があります。
これが双方向ストリーム通信の場合、手順1.を予め実行し繋ぎっぱなしにします。 手順2.や手順3.は随時好きなタイミングで実施できます。 これは手順4.を実施するまで任意の回数手順2.や手順3.を実行できます。

node.js   socket.ioモジュールを使い、双方向通信もできる
http://m.mkexdev.net/337
メモ)
・npmプロジェクト生成
express socket
・プロジェクトのフォルダに移動し、expressモジュール、socket.ioモジュールをinstall
npm install express
npm install socket.io

http://html5dev.tistory.com/346
http://qiita.com/n0bisuke/items/cb6216dbb9c3c13a10a8

https://gist.github.com/martinsik/2031681

to serve the frontend.html direct from the chat-server.js you need to do these:
install finalhandler and serve-static with the npm
npm install finalhandler serve-static
in the file chat-server.js replace line 39
// Not important for us. We're writing WebSocket server, not HTTP server
with
    var done = finalhandler(request, response);
    serve(request, response, done);
at line 21 add these lines
var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');

var serve = serveStatic("./");
int the file frontend.html replace line 26
<script src="./frontend.js"></script>
with
<script src="./chat-frontend.js"></script>
finally call the chat page with
http://127.0.0.1:1337/frontend.html





2016년 12월 29일 목요일

XMLHttpRequest and node.js

◆サーバアプリケーション:nodejsで構築
◆クライアントからサーバへの要求を非同期で行う:XMLHttpRequest

index.js
・Httpサーバ開始させる(server.js呼び出し)
・サーバ開始時に※①routerモジュールの関数、※②handlerモジュールのリクエスト処理オブジェクトをパラメータで渡す

server.js
・Httpサーバインスタンス生成、
・Httpサーバ開始、待機(http://127.0.0.1:3000)
・リスナー登録
index.jsから渡されたrouterモジュールの関数を呼び出す(パラメータは、リクエストhandleオブジェクト、リクエストのurlパス名、レスポンス)


※①router
リクエストのurlを識別し、リクエストhandlerを呼び出す
・識別できないリクエストのurlの場合、エラーメッセージをテキスト形式でレスポンスする

※②handler
リクエストのurlのパスをキー、処理関数をvalueとするオブジェクトと、様々なリクエストに対して処理関数を実装

index.html
・url --> http://127.0.0.1:3000/indexでリクエストした表示されるリソース
・ボタンをクリックしたら、<div>タグの属性id(content)に対してXMLHttpRequestインスタンスを使い、非同期通信を行い、サーバーからの受信結果



---------------------------------------------------------
index.js
---------------------------------------------------------
var server = require('../js/server');
var router = require('../js/router');
var handler= require('../js/handler');

server.start(router.route, handler.handle);
---------------------------------------------------------
server.js
---------------------------------------------------------
var http = require('http');
var url = require('url');

var server = http.createServer();

function start(route, handle){

server.addListener('request', function(request, response){
var pathName = url.parse(request.url).pathname; // ex. --> /index
console.log(pathName);
route(handle, pathName, response);
//response.writeHead(200, {'Content-Type': 'text/plain'});
//response.end('Hello World');
});

server.listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
}


// グローバル変数のexportsを使いstart()メソッドをモジュールとして登録
exports.start = start;
------------------------------------------------------------------
router.js
------------------------------------------------------------------
function route(handle, pathname, response) {
    console.log('about to route a request for ' + pathname);
    console.log('typeof handle[path] : ' + typeof handle[pathname]);
 
    if (typeof handle[pathname] === 'function') {
        handle[pathname](response);
    } else {
        console.log('no request handler found for ' + pathname);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('no request handler found for ' + pathname);          
    }
}

exports.route = route;
--------------------------------------------------------------------
handler.js
--------------------------------------------------------------------
function index(response) {
    console.log('request handler called --> index');
var fs = require('fs');
fs.readFile("../html/index.html", function(errors, data){
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(data);
});

}

function content(response) {
var fs = require('fs');
fs.readFile("../html/content.html", function(errors, data){
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(data);
});  
}

function menu(response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hellow menu!');  
}

var handle = {}; // javascript object has key:value pair.
handle['/'] = index;
handle['/menu'] = menu;
handle['/index'] = index;
handle['/content'] = content;

exports.handle = handle;


--------------------------------------------
index.html
---------------------------------------------
<html>
<head></head>
<body>
<div>index!!</div>
<div><button id="btn">click!</button></div>
<div id="content"></div>
<script type="text/javascript">
(function (){
var btnEl = document.getElementById('btn');
debugger;
btnEl.onclick = exe;
var xmlHttp;

function exe(){
createXMLHttpRequest();
var url = "/content";
                       // サーバからレスポンスを受信した場合
xmlHttp.onreadystatechange = loader;
                        // リクエスト生成 
xmlHttp.open("GET", url, true);
xmlHttp.send(null); // Post処理の場合
}

function createXMLHttpRequest() {
if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}

function loader() {
                         // サーバーからすべて受信した場合
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
                                      // レスポンスボディをテキストで返す場合
var result = xmlHttp.responseText;
document.getElementById("content").innerHTML = result;
}
}
}

})();
</script>
</body>
</html>
------------------------------------------------------------------------
content.html
------------------------------------------------------------------------
<html>
<head></head>
<body>
<div style="border:1px solid red;">result!!!

<div id="result"></div>
</div>
</body>
</html>
-------------------------------------------------------------------------

C:\WORK\DEV\NODE>tree /f  servertest2 > tree.txt


C:\WORK\DEV\NODE\SERVERTEST2
├─html
│      content.html
│      index.html
│    
└─js
        handler.js
        index.js
        router.js
        server.js

------------------------------------------------------------------------
C:\work\dev\node\servertest2\js>node index.js

ブラウザから、http://127.0.0.1:3000/index



     












XMLHttpRequest

http://ggoreb.tistory.com/122

XMLHttpRequestについて(AJAX)

XMLHttpRequestを使うとjavascriptでHTTP通信することができる。

http://wherethelightis.tistory.com/14
・Html Formタグでサーバーとの通信ができるが、javascriptでXMLHttpRequestを使うと
サーバーにデータのリクエストができる。
・HTTP:ウェブサーバーとクライアント(ウェブブラウザ)が文書を交換するための(通信)通信規約
ウェブで使うプロトコルでTCP/IPを基盤とする

1. XMLHttpRequest生成
2.リクエスト送信の準備(リクエスト作成)
3.コールバック関数作成(サーバーからのレ
スポンスが返ってきた時(読み込み完了))
・通信の状況に変化があるとonreadystatechangeで検出できる
・readyStateプロパティは、接続の状況を表す。4はサーバからのすべての応答を受信完了

Http状態コード
2xx : クライアントのリクエストをサーバーが処理成功
4xx:  クライアントのリクエストエラー
        404(リクエストのページがみつからない)
5xx:サーバエラー
        500(サーバエラー)
https://ko.wikipedia.org/wiki/HTTP_%EC%83%81%ED%83%9C_%EC%BD%94%EB%93%9C

4.リクエスト送信

※クロスドメイン通信ができる

Aサーバーから既に読み込んだWebページ上より、 
異なるドメインのサーバー(Bサーバー)に Ajax(XMLHttpRequest)を用いてデータアクセスを行なうと、 
ブラウザーのセキリュティーエラーが発生しAjax通信を行なうことができないという問題がある。


回避方法
【 JSONの使用 】
異なるドメインデータをXMLHttpRequestではなく、javascript外部ファイルをリクエストすることにより呼び出しJSONデータを取得する
「例」
<script src="http://192.168.1.1/htdocs/js/SMPL.JSON"></script>


http://www.as400-net.com/tips/httpsvr/101.html

node.js

http://www.nextree.co.kr/p8574/
http://blog.saltfactory.net/node/using-single-javascript-code-on-front-and-server-side.html


Node.jsは、jsでサーバアプリケーションを構築するためのフラットフォーム


1. httpサーバを構築するために、node.jsのhttpモジュールをロード


2.httpサーバのインスタンスを生成し、サーバーを開始して、リクエストを待機


3.リクエストイベント発生時の処理を作成(画面にHello World表示)

リスナー登録方法は、下記の通り。

①無名関数でリクエストのリスナーを登録
②Httpサーバーインスタンスを生成時、onRequestという関数を渡すことでリスナーを登録
③Httpサーバーインスタンスを生成してからリクエストイベントのリスナーを登録する
 ・リクエストイベント以外も、様々なイベントのリスナーが登録できるように作成




// Httpサーバーを構築するためには、node.jsのhttpモジュールを使用
// httpモジュールはrequire()グローバルメソッドを使い、ロードできる

var http = require('http');

// Httpサーバーインスタンス生成は、httpモジュールのcreateServer関数を使う
// サーバインスタンスのlisten関数を使い、サーバーを開始し、リクエストを待機する
// サーバはリクエストに応答するためにコールバック関数が登録され、responseで応答する
// リクエストのイベントが発生したら、コールバック関数が呼び出されて、
// 'Hello World’を画面に表示させる

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, '127.0.0.1');

console.log('Server running at http://127.0.0.1:3000/');

// Httpサーバはサーバインスタンス生成時、リスナーを登録しないとリクエストを処理できない
// このようなリスナーは関数で定義する
// 上記は、無名関数としてリクエストを処理するリスナーを登録している




var http = require('http');

function onRequest(request, response){
response.writeHead(200, {'Content-type' : 'text/plan'});
response.write('Hellow World');
response.end();

}

// httpサーバインスタンスを生成時、onRequestという関数を渡すことでリクエストのリスナーを登録する
http.createServer(onRequest).listen(3000);




var http = require('http');
var server = http.creatServer();

// requestイベントのリスナーを登録
server.addListener('request', function(request,respnse){
console.log('requested...');
response.writeHead(200, {'content-Type':'text/plain'});
response.write('Hello World');
response.end();

});

// クライアント接続イベント発生時の処理を行うリスナー登録
server.addListener('connection', function(socket)){
console.log('connected..');
});

server.listen(3000);






2016년 12월 18일 일요일

javascript3

1.クロージャ(Closure)

2.正規表現

3.apply

4.call



1.クロージャとは、変数と関数が一体化となったもの。
  関数内の変数は、関数の処理が終わると破棄されますが、
  クロージャでは、変数への参照が残るため、ガーベージコレクションの対象にならない。

  ※ポイント
   ・関数がネスト構造であること
  ・ネスト構造の内部関数から外部関数の変数への参照が存在すること

 function add(){
   var a = 1;
   return function(){ return a++};
 }
 var a = add();
 document.write(a()); // 1
 document.write(a()); // 2
 document.write(a()); // 3

javascript 練習2

1.関数
2.関数リテラル
3.コンストラクタ関数
4.Function()コンストラクタ
5. メソッド


1. 一度の定義だけでプログラムから何度も実行や呼び出しが行えるjavascriptコード部分
function talk(name){ return  'I am ' + name;}
talk('mimi');

2. 関数リテラルは著名関数を定義する式
  関数との大きい違いは、関数名がないところ

var person = function(name){ return  ' I am ' +name;};
person('mimi');


3.インスタンス化したオブジェクトを参照したい時定義(オライリー154page)
 ・初期化処理が行える。
 ・プロパティ、メソッド定義して、インスタンス化したオブジェクトから参照できる。
 ・プロパティは、インスタンス毎に異なる値の場合、定義
 ・メソッドは、インスタンスで共有できる場合 --> プロトタイプオブジェクトに追加
  ※たくさんのオブジェクトがプロパティを継承し共有できるので、使用するメモリを大幅に節約できる。

 function Person(name, age){
   this.name = name; // this --> 呼び出しオブジェクト
   this.age = age; this.play = function(){return 'play!!!'};
 };

 Person.prototype.talk = function(){
   return 'hellow' + 'I am ' + this.name + '. ' + this.age + 'years old. '
};

 var person1 = new Person('mimi', 18);
 document.write(person1.talk());
 Person.prototype.sleep = function(){return 'goodNight~'};
 document.write(person1.sleep() + '');
 document.write(person1.hasOwnProperty('name') + ''); // true
 document.write(person1.hasOwnProperty('sleep') + ''); // false(継承されたプロパティのため)
 document.write(person1.hasOwnProperty('play') + ''); // true

4.Function()コンストラクタを使い関数を定義
var person = new Function('x', 'y', 'return x * y');
 document.write(person(2, 9));
・呼び出す度に関数の本体が解釈され(コンパイルされる)、新しい関数オブジェクトが生成されるため、頻繁に使われる場合、効率が悪い
・関数リテラルや関数を使う場合、ループの中で使われたり、たくさん使っても使う度にコンパイルされるわけではない
・Function()コンストラクタが生成する関数は、静的スコープを使わない、
常にトップレベルの関数としてコンパイルされる。
var y= 'Guest';
function person(){
   var y= 'mimi';

   return new Function('return y');
}
document.write(person());


5.オブジェクトのプロパティとして、処理を定義
 var person = {name: 'guest', talk: function (talk) { return 'hello! My name is ' + this.name + talk; }}; person.name='mimi';
 document.write(person.talk(' ^^'));

2016년 12월 17일 토요일

javascript 練習1

var obj = {key1:'val1',key2:'val2'};


1.objからキーのkey2がある場合、key2の値を取得してください。

2. objからkey1のプロパティがある場合、key1の値を取得してください。

3.objにkey1を値を取得するメソッド(getKey1)を追加して、メソッドから値を取得してください。

4. 上記のメソッドの呼び出し結果が'val1です。'が取得できるようにしてください。

5. objのすべてのキーを順次に取得1

6. objのすべてのキーを順次に取得2

7. function文を作成してください。
  ・arguments[0] --> name
    ・hello!, name --> パラメータがある場合は、パラメータ表示、ない場合は、「guest」を表示

8. 上記を関数リテラルによる定義にしてください。
    プロパティ:name, age, talkIntro()--> name, ageをパラメータ、
    talkIntro処理 --> My name is  $name. $age years old.
 
8-1. new演算子でインスタンス化して処理
8-2 new演算子を使わず、関数を呼び出して処理
8-3. new演算子でインスタンス化して、プロパティ[sleep]を追加、sleep呼び出し処理('gooNight');

↓↓↓↓  hint  ↓↓↓↓↓↓


1.objからキーのkey2がある場合、key2の値を取得してください。(hint:in)

2. objからkey1のプロパティがある場合、key1の値を取得してください。(hint:hasOwnPropperty)


3.objにkey1を値を取得するメソッド(getKey1)を追加して、メソッドから値を取得してください。


4. 上記のメソッドの呼び出し結果が'val1です。'が取得できるようにしてください。(hint:arguments)


5. objのすべてのキーを順次に取得1(hint:Object key)


6. objのすべてのキーを順次に取得2(hint:Object プロパティ名をす


7.function fun(name){ var result = name || 'guest';  return 'hellow!,' + result  };


8.

var person = function (name, age) {
 this.name = name;
 this.age = age;
 this.talkIntro = function(){
    return 'hellow!,' + 'My name is ' + this.name + '.' + age + 'years old.' }; return talkIntro();
 };
 8-1.console.log(person('mimi', '100'));
 8-2.var mimi = new person('mimi',18);
 console.log(mimi.talkIntro());
 8-3.
 mimi.sleep = function(){ return 'goodNight'}